bigpotato
bigpotato

Reputation: 27527

RxJS: takeUntil with multiple actions and different filters?

I have an Observable that I want to continue executing until:

1) the uploadActions.MARK_UPLOAD_AS_COMPLETE action is called with a certain payload

OR

2) the uploadActions.UPLOAD_FAILURE action is called with any payload

This is as far as I could get (and doesn't work):

return Observable.interval(5000)
  .takeUntil(
    action$
      .ofType(
        uploadActions.UPLOAD_FAILURE,
        uploadActions.MARK_UPLOAD_AS_COMPLETE
      )
      .filter(a => { // <---- this filter only applies to uploadActions.MARK_UPLOAD_AS_COMPLETE
        const completedFileHandle = a.payload;
        return handle === completedFileHandle;
      })
  )
  .mergeMap(action =>
    ...
  );

Is there a clean way I could achieve this?

Upvotes: 6

Views: 9262

Answers (1)

bygrace
bygrace

Reputation: 5988

I'd split the two conditions into separate streams and then merge them like so:

const action$ = new Rx.Subject();
const uploadActions = {
  UPLOAD_FAILURE: "UPLOAD_FAILURE",
  MARK_UPLOAD_AS_COMPLETE: "MARK_UPLOAD_AS_COMPLETE"
};
const handle = 42;

window.setTimeout(() => action$.next({
  type: uploadActions.MARK_UPLOAD_AS_COMPLETE,
  payload: handle
}), 1200);

Rx.Observable.interval(500)
  .takeUntil(
    Rx.Observable.merge(
      action$.filter(x => x.type === uploadActions.UPLOAD_FAILURE),
      action$.filter(x => x.type === uploadActions.MARK_UPLOAD_AS_COMPLETE)
      	.filter(x => x.payload === handle)      
    )
  ).subscribe(
    x => { console.log('Next: ', x); },
    e => { console.log('Error: ', e); },
    () => { console.log('Completed'); }
  );
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/5.5.6/Rx.min.js"></script>

For the example I had to use the filter operator instead of ofType since ofType is an redux thing.

Upvotes: 8

Related Questions