我想使用BehaviorSubject取消订阅另一个使用takeUntil的Observable。当我使用takeUntil订阅Observable时,它似乎立即取消订阅。此代码适用于Subject,但我想要一个初始值集。
我正在使用rxjs 5.5.6
//MyService1
class Observable1 {
status1: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(false);
displayStatus1(val: boolean) {
this.status1.next(val)
}
}
//MyService2
class Observable2 {
status2: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(false);
displayStatus2(val: boolean) {
this.status2.next(val)
}
}
//MyComponent
status: boolean;
constructor(private myService1: MyService1, private myService2: MyService2) {
this.subscribeToObservable1();
this.subscribeToObservable2();
}
subscribeToObservable1() {
this.myService1.status1.subscribe((val: boolean) => {
console.log('val: ', val);
}
}
subscribeToObservable2() {
this.myService2.status2
.takeUntil(this.myService1.status1)
.subscribe((val: boolean) => {
this.status = val;
}
}
答案 0 :(得分:0)
当然,您可以使用skip()跳过第一个初始值:
this.status2$
.pipe(
takeUntil(
this.status1$.pipe(skip(1))
),
)
.subscribe((val: boolean) => {
// I execute until status1$ emits
}
Btw:从RxJS> = 5.5开始,您可以在我的示例中使用pipe。另外,您可以在结尾处用$
来命名您的可观察对象,以便其读取“ status1stream”
答案 1 :(得分:0)
您也可以使用过滤器。
const source = new Subject();
const destory$ = new BehaviorSubject<boolean>(false);
source
.pipe(takeUntil(destory$.pipe(filter((v: boolean) => v))))
.subscribe(resp => {
console.log("resp", resp);
});
source.next("hello");
source.next("hello2");
destory$.next(true);
destory$.complete();
source.next("hello 3 ");
答案 2 :(得分:-1)
BehaviorSubject将具有初始值。
因此,只要您的takeUntil
内部订阅,它就会释放其初始值。
见(这里)[http://reactivex.io/documentation/subject.html]
When an observer subscribes to a BehaviorSubject, it begins by emitting the item most recently emitted by the source Observable (or a seed/default value if none has yet been emitted) and then continues to emit any other items emitted later by the source Observable(s).
改为使用PublishSubject
。
答案 3 :(得分:-2)
您在takeWhile
之后:( 因为takeUntil没有采用谓词)。
var bs = new Rx.BehaviorSubject<boolean>(false); //create beahviour subject
const source = Rx.Observable.interval(1000); //create observable
// take from obs while , behaviour subject not emitting true
const example = source.takeWhile ((a)=>bs.value!=true);
const subscribe = example.subscribe(val => console.log(val));
setTimeout(()=>bs.next(true),3000); //make the BehaviorSubject emit true and stop.