Reader monad inside RxJs mergeMap

242 views Asked by At

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?

1

There are 1 answers

5
backtick On

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.