简体   繁体   中英

Combine subject and observable and wait for subject to emit a value then emit observable

I have one subject and observable, I want to combine them and emit the observable value and do some stuff with it after subject got new value. This code below works good but I don't want to have subscribe in subscribe

this.subject.subscribe(() => {
    this.observable.subscribe(b => {
      this.someStuffToDo(b);
    });

So the workflow is: next is invoked on subject -> observable is emitting value -> do some stuff with this value. I already tried combineLatest and zip, but it stops on the first emit of subject, or the order is wrong.

If you are using RxJS 6, you may consider using pipeable operators such as switchMap . The switchMap will allows you to map the observable values into the inner observable, removing the need to nest subscriptions.

this.subject
  .pipe(
    switchMap(() => this.observable),
  ).subscribe((b) => {
    this.someStuffToDo(b);
  });

And calling next() on subject will update its values.

this.subject.next(value);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM