zoukankan      html  css  js  c++  java
  • [RxJS] Hot Observable, by .share()

    .share() is an alias for .publish().refCount().

    So if the source is not yet completed, no matter how many subscribers subscribe to the source, they share the same source. 

    const clock$ = Rx.Observable.interval(500).share().take(6);
    
    const randomNum$ = clock$
      .map(i => Math.random() * 100).share();
    
    const smallNum$ = randomNum$
      .filter(x => x <= 50)
      .toArray();
    
    const largeNum$ = randomNum$
      .filter(x => x > 50)
      .toArray();
    
    randomNum$.subscribe(x => console.log('random: ' + x));
    smallNum$.subscribe(x => console.log('small:', x));
    largeNum$.subscribe(x => console.log('large:', x));
    
    /*
    
    Console Run  Clear
    "random: 49.87840398986816"
    "random: 75.01024609865293"
    "random: 32.59613439667008"
    "random: 63.4234109489461"
    "random: 35.58020574147034"
    "random: 74.94599860014348"
    "small:"
    [49.87840398986816, 32.59613439667008, 35.58020574147034]
    "large:"
    [75.01024609865293, 63.4234109489461, 74.94599860014348]
    */

    It is important to know share the same source is only before the source stream completed, if it is already completed, then the new subscribers will trigger another source running.

    For example, in the code, we change largeNum$ happens after 4s of first subscriber.

    setTimeout(() => largeNum$.subscribe(x => console.log('large:', x)), 4000)

    Because source will complete after 3s, therefor it will trigger a new source:

    /*
    "random: 74.91154828671043"
    "random: 10.964684522348733"
    "random: 29.076967396825903"
    "random: 20.070493440627235"
    "random: 22.44421045844409"
    "random: 14.233614544120798"
    "small:"
    [10.964684522348733, 29.076967396825903, 20.070493440627235, 22.44421045844409, 14.233614544120798]
    "large:"
    [93.04544926644354, 65.4090612653734, 67.15475480984114]
    */

    As we can see, in the large array, all the numbers are not from random we log out before.

  • 相关阅读:
    学习设计模式之中介者模式
    学习设计模式之责任链模式
    学习设计模式之命令模式
    学习设计模式之桥接模式
    学习设计模式之单例模式
    学习设计模式之迭代器模式
    Spring 源码学习——注册 BeanDefinition
    Html.DropDownListFor
    Home vs2013
    Jquery 操作页面中iframe自动跟随窗口大小变化,而页面不出现滚动条,只在iframe内部出滚动条
  • 原文地址:https://www.cnblogs.com/Answer1215/p/6925452.html
Copyright © 2011-2022 走看看