简体   繁体   中英

Using takeUntil to complete an RxJS stream

I want to complete an inner stream that doesn't naturally complete, using the takeUntil operator, like this:

  outerObservable
    .mergeMap(() => {
        innerObservable
            .takeUntil(stopObservable$)
    });

This works, the inner stream completes as expected, but I would like for the outer stream to return one last value after the stop signal. Even after lots of googling, I still don't know how.

EDIT:

I've written an operator that seems to do the trick, but leaving the question open because I know there's a better way or something I'm completely misunderstanding.

 function takeUntilThen(notifier, oneLastValue) { return Rx.Observable.create(subscriber => { var source = this; notifier.subscribe(() => { subscriber.next(oneLastValue); subscriber.complete() }); return source.subscribe(value => { subscriber.next(value); }, err => subscriber.error(err), () => subscriber.complete()); }); } 

Sounds like you want to race between innerObservable and stopObservable and Whichever wins, should be able to output something .

You can use the aptly named .race() operator for this, instead of using .takeUntil() . See the example in the redux-observable docs recipe on Cancellation:

https://redux-observable.js.org/docs/recipes/Cancellation.html#cancel-and-do-something-else-eg-emit-a-different-action

const somethingEpic = action$ =>
  action$.ofType(SOMETHING)
    .mergeMap(action =>
      innerObservable
        .race(
          stopObservable
            .take(1)
        )
    );

Since your example is pseudo code, here's one that's more concrete:

import { ajax } from 'rxjs/observable/dom/ajax';

const fetchUserEpic = action$ =>
  action$.ofType(FETCH_USER)
    .mergeMap(action =>
      ajax.getJSON(`/api/users/${action.payload}`)
        .map(response => fetchUserFulfilled(response))
        .race(
          action$.ofType(FETCH_USER_CANCELLED)
            .map(() => incrementCounter())
            .take(1)
        )
    );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM