当任何给定的观测值发出值时,如何运行分接算子?

时间:2019-08-13 02:34:37

标签: angular rxjs

const annotationEvent = event1$.pipe(
      filter(({ type }) => type === DemoEvent.select || type === DemoEvent.unselect),
      delay(100),
      throttleTime(50),
      tap(_ => doSomething())
    );
    const imageApplicationEvent = event2$.pipe(
      filter(({ type }) => type === TestEvent.selectItem || type === TestEvent.unselectItem),
      delay(100),
      throttleTime(50),
      tap(_ => doSomething())
    );
forkJoin([annotationEvent, imageApplicationEvent]).subscribe();

上面的代码event1$event2是一个长寿命的Observable,由behaviorSubject.asObservable返回。如您所见,在过滤了发射值的类型之后,编写了重复的代码。我试图在任何给定的Observable(在这种情况下为doSomethingevent1$)发出值时运行event2$方法。我假设对forkJoin运算符tap进行管道运算会使用更简单的代码完成相同的操作。像这样

const annotationEvent = event1$.pipe(
      filter(({ type }) => type === DemoEvent.select || type === DemoEvent.unselect)
    );
    const imageApplicationEvent = event2$.pipe(
      filter(({ type }) => type === TestEvent.selectItem || type === TestEvent.unselectItem)
    );
forkJoin([annotationEvent, imageApplicationEvent]).pipe(
      delay(100),
      throttleTime(50),
      tap(_ => doSomething())).subscribe();

但是似乎它没有按我预期的那样工作,并且我假设forkJoin仅在所有给定的可观察值都完成时才发出最后一个发出的值,并且由于event1$event2$未完成,所以它没有以我期望。我尝试了zipcombineLatest或类似的可观察者分组的运算符,但没有一个能达到我想要的目的。

结论,当任何给定的可观察对象发出值时,是否有任何可能的方法来运行代码?

1 个答案:

答案 0 :(得分:1)

我认为您正在寻找“合并”运算符, 例如

const annotationEvent = event1$.pipe(
      filter(({ type }) => type === DemoEvent.select || type === DemoEvent.unselect)
    );

const imageApplicationEvent = event2$.pipe(
      filter(({ type }) => type === TestEvent.selectItem || type === TestEvent.unselectItem)
    );

merge(annotationEvent, imageApplicationEvent).pipe(
      delay(100),
      throttleTime(50),
      tap(_ => doSomething())).subscribe();