简体   繁体   English

合并主题和可观察对象,等待对象发出一个值,然后发出可观察对象

[英]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. 我已经尝试过CombineLatest和zip,但是它在主题的第一次发出时停止,或者顺序错误。

If you are using RxJS 6, you may consider using pipeable operators such as switchMap . 如果您使用的是RxJS 6,则可以考虑使用可切换的运算符,例如switchMap The switchMap will allows you to map the observable values into the inner observable, removing the need to nest subscriptions. switchMap将允许您将可观察值映射到内部可观察值,而无需嵌套订阅。

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

And calling next() on subject will update its values. 并在subject上调用next()将更新其值。

this.subject.next(value);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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