0

I am using rxjs and want to use Reader monad from fp-ts package as a Dependency Injection solution.

Here is my code:

import { of } from 'rxjs';
import { pipe } from 'fp-ts/function';
import { mergeMap } from 'rxjs/operators';
import * as R from 'fp-ts-rxjs/ReaderObservable';

type Dependency = { dep1: string }

const fn1 = (input: string): R.ReaderObservable<Dependency, string> => (dep: Dependency) =>
  of(`${input} | ${dep.dep1}`);

const fn2 = () => pipe(
  of('initial').pipe(
    mergeMap(x => pipe(
      fn1(`| inside merge map ${x}`),
    )),
  ),
);

fn2()({dep1: "something"}).subscribe(
  data => console.log(data),
);

fn1 function has a dependency that is injected using Reader monad

The problem is when I use this function inside a mergeMap the return value is a ReaderObservable and not an Observable and causes errors.

How can I use ReaderObservable inside a mergeMap?

mohsen saremi
  • 685
  • 8
  • 22

1 Answers1

0

It doesn't work because mergeMap's callback must return either an Observable or an ObservableInput:

type ObservableInput<T> = SubscribableOrPromise<T> | ArrayLike<T> | Iterable<T>;

But a ReaderObservable is a function that returns an Observable.

Anything that expects Observable | ObservableInput won't be able to use it without actually invoking it with the dependency.


So how can you use it? Well, at what point is your dependency actually going to be injected? Your code example doesn't show the actual point of injection. At a minimum, the dependency must be in scope within the mergeMap callback so you can convert the ReaderObservable to an actual Observable.

backtick
  • 2,685
  • 10
  • 18
  • `fn2` doesn't know about `fn1` dependency. How should I invoke it with the dependency inside mergeMap? The dependency will inject when I want to subscribe at the last line. `fn2().subscribe( data => console.log(data), );` – mohsen saremi Apr 25 '21 at 04:33
  • I don't see that demonstrated in the code. In what scope does the dependency exist? – backtick Apr 25 '21 at 16:36
  • I need something like this at top level where I want to send the actual dependencies: `fn2()({dep1: "something"}).subscribe( data => console.log(data), );` – mohsen saremi Apr 25 '21 at 17:24
  • OK, please update the question with the code as you think it should work. Right now you have `fn2().subscribe(...)`, which is different from your most recent comment. The code in your question should be a [mre]. – backtick Apr 25 '21 at 20:21
  • Do you have any solution? – mohsen saremi Apr 30 '21 at 11:44