zoukankan      html  css  js  c++  java
  • [Angular 2] Managing State in RxJS with StartWith and Scan

    The scan operator in RxJS is the main key to managing values and states in your stream. Scan behaves just as a reduce function would, but scan is able to collect values from streams over time. This lesson covers using startWith to set the initial accumulator value then using scan to update the value of the clock from the clicks and interval.

    import {Component} from 'angular2/core';
    import {bootstrap} from 'angular2/platform/browser';
    import {Observable} from 'rxjs/Observable';
    import 'rxjs/add/observable/interval';
    import 'rxjs/add/observable/merge';
    import 'rxjs/add/operator/map';
    import 'rxjs/add/operator/scan';
    import 'rxjs/add/operator/startWith';
    import {Subject} from 'rxjs/Subject';
    
    @Component({
        selector: 'app',
        template: `
            <button (click)="click$.next()">Add one second</button>
            <h1>{{clock | async | date: 'yMMMMEEEEdjms'}}</h1>
        `
    })
    
    class App {
    
        click$ = new Subject();
        clock;
        constructor(){
    
            this.clock = Observable.merge(
                Observable.interval(1000),
                this.click$
            )
                .startWith(new Date())
                .scan( (acc: Date, curr) => {
                    const date = new Date(acc.getTime());
                    date.setSeconds(date.getSeconds() + 1);
                    return date;
                });
        }
    }
    
    bootstrap(App);
  • 相关阅读:
    python redis操作
    subprocess模块的使用
    tcpcopy 流量复制工具
    Python名称空间与闭包
    python 偏函数
    Python面向对象的特点
    vsftpd 安装及使用虚拟用户配置
    shell 并发脚本
    Centos7 搭建LVS DR模式 + Keepalive + NFS
    python pip 升级
  • 原文地址:https://www.cnblogs.com/Answer1215/p/5433555.html
Copyright © 2011-2022 走看看