简体   繁体   English

RxJs:如何关闭嵌套 observable.subscribe 调用的订阅

[英]RxJs : How to close subscription of nested observable.subscribe call

Within my Angular app :在我的 Angular 应用程序中:

i ve this treatment :我有这样的治疗:

mySubjectOne = new Subject();

methodOne(){
    this.subscriptionOne = mySubjectOne.subscribe((response) => {
      this.methodTwo();
    })
}

methodTwo(){
  this.subscriptionTwo = return this.httpClient.post(myurl , mydata).subscribe((response) => {
      myTreatment(); // MY TREATMENT
  })
}

My probleme is whenever " mySubjectOne " is called methodOne calls methodTwo ,我的问题是每当“ mySubjectOne ”被称为methodOne调用methodTwo 时

and the subscriptionTwo seems to be cloned to be +1 every time :并且 subscriptionTwo 似乎每次都被克隆为 +1

for example in the third time of calling : methodOne , it seems that there were 4 subscriptionTwo invoqued比如第三次调用:methodOne,好像调用了4个subscriptionTwo

How may i close the subsrciption subscriptionTwo just after TREATMENT and let it be recreated in each rime我如何在 TREATMENT 之后关闭 subsrciption subscriptionTwo 并让它在每个 rime 中重新创建

Suggestions ?建议?

You can use switchMap to achieve exactly this behavior.您可以使用switchMap来实现这种行为。 Note that there are also other operators such as exhaustMap or mergeMap that may fit your desired behavior even more.请注意,还有其他运算符,例如exhaustMapmergeMap ,它们可能更适合您想要的行为。 Read up on the source provided.阅读提供的来源。

mySubjectOne = new Subject();

methodOne() {
  this.subscriptionOne = mySubjectOne.pipe(
    switchMap((response) => this.methodTwo()),
  )
    .subscribe((response) => {
      myTreatment();
  });
}

methodTwo() {
  this.subscriptionTwo = return this.httpClient.post(myurl , mydata);
}

Now whenever mySubjectOne fires, methodTwo will be executed.现在每当mySubjectOne触发时, methodTwo将被执行。 Once that's done, myTreatment will run.完成后, myTreatment将运行。

Note that you should run methodOne just once (to initialize the subscription), as otherwise the subscription may run multiple times.请注意,您应该只运行一次methodOne (以初始化订阅),否则订阅可能会运行多次。 So I suggest to move the initialization process into your constructor or maybe ngOnInit .所以我建议将初始化过程移到你的构造函数或者ngOnInit

I believe that is a bad idea to subscribe inside a subscription.我认为在订阅中订阅是个坏主意。 You better use SwitchMap to handle it.你最好使用SwitchMap来处理它。

If you prefer to go your way, you could use TakeUntil to emit the end of your subscription.如果您更喜欢走自己的路,您可以使用TakeUntil发出订阅的结束。

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

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