gcanti / fp-ts-rxjs

fp-ts bindings for RxJS
https://gcanti.github.io/fp-ts-rxjs/
MIT License
187 stars 29 forks source link

An alternative chainFirst'ish operator #68

Open anilanar opened 2 years ago

anilanar commented 2 years ago

🚀 Feature request

Current Behavior

pipe(of('a'), chainFirst(() => EMPTY)) is equivalent to EMPTY. pipe(of('a'), chainFirst(() => of('b'))) is equivalent to of('a'). pipe(of('a'), chainFirst(() => from(['b', 'c']))) is equivalent to from(['a', 'a']). pipe(of('a'), chainFirst(() => pipe(from(['b', 'c']), chainIOK(a => () => console.log(a))))) is equivalent to from(['a', 'a']) and prints b c.

Desired Behavior

pipe(of('a'), chainFirst(() => EMPTY)) is equivalent to of(a). pipe(of('a'), chainFirst(() => of('b'))) is equivalent to of('a'). pipe(of('a'), chainFirst(() => from(['b', 'c']))) is equivalent to of(a). pipe(of('a'), chainFirst(() => pipe(from(['b', 'c']), chainIOK(a => () => console.log(a))))) is equivalent to of('a') and prints b c.

Suggested Solution

Did anybody else need this ever?

The need for this becomes more apparent for ObservableEither, because then errors from the inner observable would be merged into the outer observable.

// I don't know what name is appropriate
const kindaLikeChainFirst = <A>(
  f: (a: A) => Observable<B>,
): ((ma: Observable<A>) => Observable<A>) =>
  pipe(ma, chain(a => pipe(f(a), $.filter(() => false), $.startWith(of(a)))));

Implementation for ObservableEither would be something like this:

// I don't know what name is appropriate
const kindaLikeChainFirst = <E, A>(
  f: (a: A) => ObservableEither<E, B>,
): ((ma: Observable<E, A>) => Observable<E, A>) =>
  pipe(ma, chain(a => pipe(f(a), $.filter(Either.isLeft), $.startWith(Either.right(a)))));
wayneseymour commented 11 months ago

I hope the following is not too orthogonal, but it "feels" like chainFirst is a "tap" fn: a fn for side effects in a composition pipeline, that runs the side-effect fn and then returns the value from the previous fn in the pipeline.

Am I way wrong here or what?