const subscription: Subscription;
const first$ // Observable A
const second$ // Observable B
// When `first$` emits, I am checking the value and
// subscribe to `second$` if value is more than 5
subscription.add(
first$.subscribe(value => {
if(value > 5) {
subscription.add(
second$.subscribe((name) => console.log(name))
);
}
});
);
first$
可能会在应用程序的整个生命周期(角度)中继续发出多个值。如何确保second$
在被订阅后不会再次被订阅?
答案 0 :(得分:1)
尝试switchMap:
this.second$ = this.first$.pipe(
filter(v => v > 5),
// take(1), // if necessary
switchMap(v => this.doSomethingAsyncWith()),
);
答案 1 :(得分:0)
您可以先过滤,然后订阅一个:
first$.pipe(filter(v => v > 5), first()).subscribe(() => second$.subscribe((name) => console.log(name)))
答案 2 :(得分:0)
SwitchMap:
import { BehaviorSubject, EMPTY, interval } from 'rxjs';
import { map, switchMap, tap } from 'rxjs/operators';
const first$ = interval(1000).pipe(
map(() => Math.random() * 10)
);
const $second = new BehaviorSubject('second obs');
first$.pipe(
tap(resultFirst => console.log('resultFirst', resultFirst)),
// conditionally subscribe to $second
switchMap(resultFirst => resultFirst > 5 ? $second : EMPTY),
tap(resultSecond => console.log('resultSecond', resultSecond)),
).subscribe();
switchMap
将自动取消订阅内部可观测对象,以防外部可观测对象发出新值。
https://www.learnrxjs.io/operators/transformation/switchmap.html
答案 3 :(得分:0)