RxJs: Calculating observable array length in component

我的未来我决定 提交于 2019-12-13 03:57:19

问题


I have an observable array, purchases$. In my angular 2 component I'd like to calculate the length of the array. I worry that the observable is never complete and thus my subscriptions end up piling up. If I do the following will the subscription be complete?

this.purchases$.subscribe((val) => {
  val.length > 0 ? this.purchaseType = 'initial' : this.purchaseType = 'additional'
})

Once I have an initial value I am happy to unsubscribe.

Can I simple add .unsubscribe() to the end?


回答1:


What you have in your subscriptions doesn't affect the source Observable so if you want to unsubscribe you need to use an operator that completes the chain or unsubscribe manually.

For example if you know how many items you want to accept you can use take(N) or if it depends on a certain condition you can use takeWhile(). Or you can collect items with scan() and combine it with takeWhile() for example.

You can also unsubscribe right in your subscribe call:

this.purchases$.subscribe(function(val) {
  if (condition) {
    this.unsubscribe();
  }
});

Note that in this case you can't use arrow functions () => ... because RxJS binds this context to the current Subscription object. That's why you can call this.unsubscribe() and unsubscribe (this is not a hack, it's intended to be used this way).




回答2:


Rather than imperatively unsubscribing, i'd recommend you use the first operator to make an observable that automatically completes after the first result is emitted:

this.purchases$.pipe(first()).subscribe((val) => {
  val.length > 0 ? this.purchaseType = 'initial' : this.purchaseType = 'additiona';
})


来源:https://stackoverflow.com/questions/52500728/rxjs-calculating-observable-array-length-in-component

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!