zoukankan      html  css  js  c++  java
  • [RxJS] Updating Data with Scan

    You often need to update the data flowing through the stream with custom logic based on what you need to output. This lesson covers how to use scan for collecting and updating the outputs as your stream progresses.

    EVerytime we click start button now it will start from 0:
    const Observable = Rx.Observable;
    
    const startButton = document.querySelector('#start');
    const stopButton = document.querySelector('#stop');
    
    const start$ = Observable.fromEvent(startButton, 'click');
    const interval$ = Observable.interval(1000);
    const stop$ = Observable.fromEvent(stopButton, 'click');
    
    const intervalThatStop$ = interval$.takeUntil(stop$);
    
    
    start$.switchMapTo(intervalThatStop$)
      .subscribe( (x) => {
      console.log(x);
    })

    What we want is it should remeber the current state, so that, next time when we start again, it can use our current state:

    const Observable = Rx.Observable;
    
    const startButton = document.querySelector('#start');
    const stopButton = document.querySelector('#stop');
    
    const start$ = Observable.fromEvent(startButton, 'click');
    const interval$ = Observable.interval(1000);
    const stop$ = Observable.fromEvent(stopButton, 'click');
    
    const intervalThatStops$ = interval$
        .takeUntil(stop$);
    
    start$
        .switchMapTo(intervalThatStops$)
        .scan( (acc) => {
            return Object.assign(acc, {count: acc.count + 1})
        }, {
           count: 0
        })
        .subscribe((x)=> console.log(x));
  • 相关阅读:
    hdu 4597 记忆化搜索
    hdu 4494 最小费用流
    hdu 4598 差分约束
    poj 3621 0/1分数规划求最优比率生成环
    poj 1695 动态规划
    noi 97 积木游戏
    hdu 4705 排列组合
    洛谷P2014 选课
    洛谷P1776 宝物筛选
    洛谷P1782 旅行商的背包
  • 原文地址:https://www.cnblogs.com/Answer1215/p/5258786.html
Copyright © 2011-2022 走看看