6

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?

bigpotato
  • 26,262
  • 56
  • 178
  • 334
  • What specifically doesn't work? My gut reaction would be to do a `combineLatest` on two separate `action$.ofType(...)` so you could filter the one. – bygrace Feb 09 '18 at 16:29
  • @bygrace Because it's applying the `filter` to `uploadActions.UPLOAD_FAILURE`, which doesn't have a payload and therefore returns false – bigpotato Feb 09 '18 at 16:30

1 Answers1

8

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.

bygrace
  • 5,868
  • 1
  • 31
  • 58
  • Perfect! I used the Observable.merge thing and ended up with: `Observable.merge(action$.ofType(...).filter(...), action$.ofType(...))` Thanks! – bigpotato Feb 09 '18 at 16:42