zoukankan      html  css  js  c++  java
  • [RxJS] Resubscribing to a Stream with Repeat

    When you complete a stream, there’s no way to restart it, you must resubscribe. This lesson shows how repeat comes in handy to resubscribe after a stream has completed.

    Current this block of code:

    const timer$ = starters$
        .switchMap(intervalActions)
        .startWith(data)
        .scan((acc, curr)=> curr(acc))
    
    
    timer$
        .do((x)=> console.log(x))
        .takeWhile((data)=> data.count <= 3)
        .withLatestFrom(
            input$.do((x)=> console.log(x)),
            (timer, input)=> ({count: timer.count, text: input})
        )
        .filter((data)=> data.count === parseInt(data.text))
        .reduce((acc, curr)=> acc + 1, 0)
        .subscribe(
            (x)=> console.log('Score', x),
            err=> console.log(err),
            ()=> console.log('complete')
        );
    
    /**
    "Score"
    0
    "complete"
    **/

    Once it hit complete block, you can never start the timer again. THis is because the stream is completed, so if we want able to re-subscribe many times, we can use repeact() method:

    timer$
        .do((x)=> console.log(x))
        .takeWhile((data)=> data.count <= 3)
        .withLatestFrom(
            input$.do((x)=> console.log(x)),
            (timer, input)=> ({count: timer.count, text: input})
        )
        .filter((data)=> data.count === parseInt(data.text))
        .reduce((acc, curr)=> acc + 1, 0)
        .repeat() // repact the block of code above
        .subscribe(
            (x)=> console.log('Score', x),
            err=> console.log(err),
            ()=> console.log('complete')
        );

    Now we are able to repact the stream, but it will never hit the complete block, but it is ok.

    And also should be careful when use repeact(); you cannot put it anywhere you want, if you put it before fiilter(), then it willl never hit the filter block, so usually should put it right before the subscribe() method.

  • 相关阅读:
    【C++模版之旅】静态多态的讨论
    UBI(unsorted block image )块管理
    CSS多级数字序号的目录列表(类似3.3.1.这样的列表序号)
    MyBatis映射文件的resultMap如何做表关联
    爱上演讲的程序猿
    PHP中文汉字验证码
    设计模式之(二)Adapter模式
    sphinx全文检索之PHP使用教程
    [置顶] 【cocos2d-x入门实战】微信飞机大战之十三:游戏场景过渡
    计算机的族谱
  • 原文地址:https://www.cnblogs.com/Answer1215/p/5273222.html
Copyright © 2011-2022 走看看