RxJS:takeUntil有多个动作和不同的过滤器?

时间:2018-02-09 15:54:59

标签: rxjs redux-observable

我有一个Observable,我想继续执行,直到:

1)使用特定有效负载调用uploadActions.MARK_UPLOAD_AS_COMPLETE动作

OR

2)使用任何有效负载调用uploadActions.UPLOAD_FAILURE动作

这是我能得到的(并且不起作用):

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 =>
    ...
  );

我能做到这一点吗?

1 个答案:

答案 0 :(得分:4)

我将这两个条件分成不同的流,然后合并它们:

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>

对于示例,我必须使用filter运算符而不是ofType,因为ofType是一个redux事物。