【问题标题】:RxJs: How to know which operators closes stream?RxJs:如何知道哪些运营商关闭了流?
【发布时间】:2019-06-12 15:53:39
【问题描述】:

我很感兴趣,有没有办法知道操作员是否关闭了流? 我一直试图在文档中找到它,但今天没有运气。

【问题讨论】:

  • 当您说“关闭”时,我猜您指的是取消订阅?如果是,那么您有两个选择 - 1. 在 .subscribe() 返回的订阅对象上调用“unsubscribe()” 或者 2. 一旦您的 observable 发出 1 个值,使用 take(1) 运算符完成您的订阅,它将自动取消订阅as observable 完成。一旦您澄清“关闭”流是什么意思,我们将能够更好地回答您的问题?
  • 当订阅者告诉 observable 没有更多值要发出时,流将 完成。没有一个操作符会触发外部 observable 以 complete。他们只能提升一个 observable 并完成一个新的内部 observable 和 取消订阅outer observable。因此,即使您使用first(),它也会在下游完成,但只能从上游可观察对象中取消订阅。如果你有一个发出值的 hot 可观察对象,那么即使没有订阅任何内容,它也会继续发出值。
  • @user2216584 正是你所说的,我怎么知道,对于你提供的例子,take,它完成了订阅,即自动取消订阅?

标签: rxjs ngrx reactivex


【解决方案1】:

我认为您正在寻找 subscribe() 方法的“complete”回调(或第三个参数)[参见 cmets 中的详细信息] -

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

请参阅以下堆栈闪电战 - https://stackblitz.com/edit/rxjs-toarray-xwvtgk?file=index.ts&devtoolsheight=100

【讨论】:

    猜你喜欢
    • 2012-05-10
    • 1970-01-01
    • 2015-02-10
    • 2018-01-09
    • 1970-01-01
    • 2014-07-09
    • 1970-01-01
    • 2013-08-15
    • 1970-01-01
    相关资源
    最近更新 更多