zoukankan      html  css  js  c++  java
  • [RxJS] Refactoring CombineLatest to WithLatestFrom

    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.

  • 相关阅读:
    MongoDB 基础学习
    在 PostgreSQL 中使用码农很忙 IP 地址数据库
    在 MySQL 中使用码农很忙 IP 地址数据库
    编译opencv和opencv_contrib
    修改本次提交日志
    clone报告超过限制
    修改gitolite管理员
    libevent简介[翻译]11 连接监听:接收一个TCP连接
    libevent简介[翻译]11 Evbuffers:缓冲IO的功能函数
    Windows查看TCP连接数
  • 原文地址:https://www.cnblogs.com/Answer1215/p/5269643.html
Copyright © 2011-2022 走看看