• [RxJS] Stopping a shared observable execution


    ConnectableObservable has the connect() method to conveniently dictate the start of the shared execution of the source Observable. However, we need a mechanism to dictate the stop of the shared execution, otherwise a leak happens. This lesson will teach you how to do that, and it's all about Subscriptions.

    var connectableObservable = Rx.Observable.interval(1000)
      .do(x => console.log('source ' + x))
      .multicast(new Rx.Subject());
    
    var observerA = {
      next: function (x) { console.log('A next ' + x); },
      error: function (err) { console.log('A error ' + err); },
      complete: function () { console.log('A done'); },
    };
    
    var sub = connectableObservable.connect(); // start
    
    var subA = connectableObservable.subscribe(observerA);
    
    var observerB = {
      next: function (x) { console.log('B next ' + x); },
      error: function (err) { console.log('B error ' + err); },
      complete: function () { console.log('B done'); },
    };
    
    var subB;
    setTimeout(function () {
      subB = connectableObservable.subscribe(observerB);
    }, 2000);
    
    setTimeout(function () {
      sub.unsubscribe(); // stop
      console.log('unsubscribed shared execution');
    }, 5000);

    Just remember that with connect we are manually controlling the start of the shared execution, and then we keep a subscription in order to manually control the stop of the shared execution. All of this is in order to avoid leaks.

  • 相关阅读:
    基础排序算法之快速排序(Quick Sort)
    基础排序算法之并归排序(Merge Sort)
    Python中With的用法
    Python中AND-OR的用法
    注解/Annotation
    初识Angular2
    Angular 2 入门二
    Angular2 入门
    asp中将系统货币符号¥改为美国货币符号$的做法
    设计模式总结
  • 原文地址:https://www.cnblogs.com/Answer1215/p/5986631.html
Copyright © 2020-2023  润新知