[RxJS] Refactoring CombineLatest to WithLatestFrom

本文展示了在特定情况下使用withLatestFrom而非combineLatest的必要性,通过实例说明了两者之间的区别及原因。

This lesson shows why it’s preferable to using withLatestFrom instead of combineLatest in certain scenarios.

 

Timer will continue until you enter the number in the input field:

timer$
    .do((x)=> console.log(x))
    .combineLatest(
        input$.do((x)=> console.log(x)),
        (timer, input)=> ({count: timer.count, text: input})
    )
    .takeWhile((data)=> data.count <= 3)
    .filter((data)=> data.count === parseInt(data.text))
    .reduce((acc, curr)=> acc + 1, 0)
    .subscribe(
        (x)=> console.log(x),
        err=> console.log(err),
        ()=> console.log('complete')
    );

 

In this case, withLatestFrom() works the same way:

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

 

But let's say we only want the timer log out 3 times then it should hit the complete block, logout "complete":

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(x),
        err=> console.log(err),
        ()=> console.log('complete')
    );

then it only works with withLatestFrom() NOT combimeLatest().

The reason for that is combimeLatest require both timer$ and input$. But withLatestFrom() only need $timer.

 

转载于:https://www.cnblogs.com/Answer1215/p/5269643.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值