How to stop a subscription after the response to a service/store has a certain argument/value [duplicate]

浪子不回头ぞ 提交于 2020-06-17 15:57:07

问题


I have, say a service, or a store selector, to be more accurate, that returns an object that changes after some time (returns a different object).

But the thing is, I want to unsubscribe from this service after this object has a certain property in it, or (later) if a property has a certain value to it.

I know i'ts usual to use the takeUntil function from 'rxjs', i've used pipe(first()) before when i just needed to get the first response from a service, or .pipe(takeuntil(destroy$)) when the component using it is destroyed ( I manipulate destroy$ )

I want to stop subscribing to a service/observable after the response I get from it has a certain property in it, or if that property has a value I deem final.


回答1:


takeWhile is a good option here. For example:

observable$.pipe(
    takeWhile(x => x.someProperty !== someValue))

Just be sure to negate the condition, as I've done above, so that values are taken while the property doesn't have the value you want. This means it will stop (and unsubscribe) once the value matches.

To get the actual value that caused takeWhile to end the subscription, pass true as a second parameter to takeWhile (inclusive):

observable$.pipe(
    takeWhile(x => x.someProperty !== someValue, true))

When the optional inclusive parameter is set to true it will also emit the first item that didn't pass the predicate.




回答2:


Just unsubscribe

subscription // as field eg


subscription=yourObservable.subscribe(()=> if whaever subscription.cancel()); //or .unsubscribe() cant remember now

or use takeUntil operator

observable.pipe(takeUntil(val=> some test ).subscribe(...);


来源:https://stackoverflow.com/questions/57762268/how-to-stop-a-subscription-after-the-response-to-a-service-store-has-a-certain-a

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