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?
It doesn't work because
mergeMap's callback must return either anObservableor anObservableInput:But a
ReaderObservableis a function that returns anObservable.Anything that expects
Observable | ObservableInputwon'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
mergeMapcallback so you can convert theReaderObservableto an actualObservable.