[RxJS] Resubscribing to a Stream with Repeat

本文介绍了如何使用repeat()方法在流完成之后进行多次订阅,即使流已完成也无法再次启动定时器。通过实例演示了如何利用repeat()方法重复执行特定代码块,并确保它不会触发完成事件,同时提供了正确放置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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值