RxJs:计算组件中的可观察数组长度 [英] RxJs: Calculating observable array length in component

查看:38
本文介绍了RxJs:计算组件中的可观察数组长度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个可观察的数组, purchases $ .在我的angular 2组件中,我想计算数组的长度.我担心可观察对象永远不会完成,因此我的订阅最终会堆积起来.如果执行以下操作,订阅将完成吗?

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.

我可以简单地在末尾添加 .unsubscribe()吗?

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

推荐答案

订阅中的内容不会影响可观察的来源,因此,如果要退订,则需要使用操作员来完成链或手动退订.

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.

例如,如果您知道要接受多少个物品,可以使用 take(N),或者如果它取决于特定条件,则可以使用 takeWhile().或者,您可以使用 scan()收集项目,然后将其与 takeWhile()组合.

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();
  }
});

请注意,在这种情况下,您不能使用箭头功能.... ,因为RxJS将 this 上下文绑定到当前的 Subscription 对象.这就是为什么您可以调用 this.unsubscribe()并取消订阅(这不是hack,它打算以这种方式使用).

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).

这篇关于RxJs:计算组件中的可观察数组长度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆