RxJs:如何知道哪些操作符关闭流?
我很感兴趣,有没有办法知道操作员是否关闭流?RxJs:如何知道哪些操作符关闭流?,rxjs,ngrx,reactivex,Rxjs,Ngrx,Reactivex,我很感兴趣,有没有办法知道操作员是否关闭流? 我一直试图在文档中找到它,但今天运气不好。我想您正在寻找subscribe()方法的“complete”回调(或第三个参数)[请参阅注释中的详细信息]- yourObservable.pipe( take(1) //or take any number of values i.e. which is a finite number, map(), //or some other operators as per y
我一直试图在文档中找到它,但今天运气不好。我想您正在寻找subscribe()方法的“
complete
”回调(或第三个参数)[请参阅注释中的详细信息]-
yourObservable.pipe(
take(1) //or take any number of values i.e. which is a finite number,
map(),
//or some other operators as per your requirement
).subscibe(
//first call back is to handle the emitted value
//this will be called every time a new value is emitted by observable
(value) => {
//do whatever you want to do with value
console.log(value);
},
//second callback is for handling error
//This will be called if an observable throws an exception
//once an exception occurred then also observable complete and no more values recieved by the subscriber
//Either complete callback is called or error callback is called but not
//both
(exception) => {
//do whatever you want to do with error
console.log(error);
},
//third callback will be called only when source observable is complete
//otherwise it will never get called
//This is the place to know if an observable is completed or not
//Once complete callback fires, subscription automatically unsubscribed
() => {
console.log(`Observable is complete and will not emit any new value`)
}
);
请参阅下面的stackblitz-当您说“关闭”时,我猜您指的是取消订阅?如果是,那么您有两个选择-1。对.subscribe()或2返回的订阅对象调用“unsubscribe()”。使用take(1)操作符完成订阅一旦observable发出1值,它将在observable完成时自动取消订阅。一旦您澄清“关闭”流是什么意思,我们将能够更好地回答您的问题。当订户告诉可观察对象没有更多的值可发射时,流将完成。没有一个操作符会触发外部可观察对象完成。他们只能提升一个可观察物,完成一个新的内部可观察物,并取消对外部可观察物的订阅。因此,即使您使用
first()
,它也将在下游完成,但只能从上游的可观察对象中取消订阅。如果您有一个正在发出值的热可观测对象,那么即使没有订阅任何内容,它也将继续发出值。@user2216584正如您所说的,我如何知道,例如您提供的示例,take
,它完成了订阅,即自动取消订阅?