【问题标题】:Difference between RxJS5 subscription and observerRxJS5 订阅和观察者的区别
【发布时间】:2017-06-16 09:41:58
【问题描述】:

我看到一些与 Rx 订阅/观察者相关的问题/答案,但它们可能适用于旧版本的 Rx,也不适用于可能符合不同 API 的 RxJS。

我的印象是订阅/订阅者和观察者都是一样的。如果您查看文档,它们位于不同的相邻部分,但似乎完全相同:

观察者: http://reactivex.io/rxjs/manual/overview.html#observer

订阅: http://reactivex.io/rxjs/manual/overview.html#subscription

到底有什么区别?有人可以举个例子说明两者之间的实际区别吗?

【问题讨论】:

    标签: rxjs5


    【解决方案1】:

    Observer 是 Observable 传递的值的消费者。

    所以基本上观察者接收流发出的值。

    Subscription 是一个代表一次性资源的对象,通常是 Observable 的执行。

    订阅基本上只是某个观察者当前接收数据的“事实”,如果您取消订阅订阅,则流和观察者仍然存在,只是不再连接.


    混合了伪代码的现实世界隐喻:报纸

    :这将是报纸的生产链(涉及出版公司创建内容和印刷厂印刷纸张)

    const newsPaper$ = Observable.interval(DAILY)
        .switchMapTo(date => publishingCompany.createContent(date))
        .switchMapTo(content => printingHouse.printPaper(content))
        .publish()
        .refCount();
    

    观察者:这将是读者/收件人,那个穿着浴袍的人每天早上在他的前院拿起报纸阅读。 p>

    const bathrobeGuy = {
        next: newsPaper => readPaper(newsPaper),
        error: errorMsg => complainAbout(errorMsg), // the bathrobe guy will be so angry, the he unsubscribes the paper
        complete: () => subscribeToDifferentNewsPaper()
    }
    

    订阅:这是报纸订阅 - 送货员每天早上把报纸扔到每个前院。

    // this will activate the "delivery boy"
    const paperSubscription = newsPaper$.subscribe(bathrobeGuy);
    

    退订:当浴袍男决定不再需要报纸时,他可以退订报纸,送货员将不再派送任何报纸。然而观察者(浴袍男)和报社仍然存在,只是已经没有任何关系了。

    paperSubscription.unsubscribe();
    

    【讨论】:

      【解决方案2】:

      Observer 是一个具有一组回调的对象,这些回调在您订阅 Observable 时执行。换句话说,当你调用subscribe 时,你传递了一个 Observer 类型的对象。即使你只传递一个回调,rxjs 内部也会创建一个观察者,你的回调作为next 属性。其他属性为errorcomplete

      Subscription 是调用subscribereturn 类型,其唯一目的是能够调用subscription.unsubscribe() 以便不再收听该订阅。 Observer 函数(next、error、complete)将不再被调用。

      var myObserver = {
        next: (val) => {},
        error: (err) => {},
        complete: () => {}
      };
      
      var mySubscription: Subscription = myObservable.subscribe(myObserver);
      
      // then, if later you want to unsubscribe:
      
      mySubscription.unsubscribe()
      

      【讨论】:

        猜你喜欢
        • 2015-02-24
        • 2021-10-30
        • 1970-01-01
        • 2013-03-13
        • 1970-01-01
        • 1970-01-01
        • 2016-06-26
        • 1970-01-01
        • 2018-06-11
        相关资源
        最近更新 更多