zoukankan      html  css  js  c++  java
  • [RxJS] Adding Conditional Logic with Filter

    Often you only want values to proceed through your stream if they meet certain criteria, just as if you were using an if statement in plain JavaScript. This lesson shows you how to use filter on your stream to only push the values that you need through your stream.

    const Observable = Rx.Observable;
    
    const startButton = document.querySelector('#start');
    const halfButton = document.querySelector('#half');
    const quarterButton = document.querySelector('#quarter');
    
    const stopButton = document.querySelector('#stop');
    const resetButton = document.querySelector('#reset');
    
    const input = document.querySelector('#input');
    
    const start$ = Observable.fromEvent(startButton, 'click');
    const half$ = Observable.fromEvent(halfButton, 'click');
    const quarter$ = Observable.fromEvent(quarterButton, 'click');
    
    const stop$ = Observable.fromEvent(stopButton, 'click');
    const reset$ = Observable.fromEvent(resetButton, 'click');
    
    const input$ = Observable.fromEvent(input, 'input')
        .map(event => event.target.value);
    
    
    const data = {count:0};
    const inc = (acc)=> ({count: acc.count + 1});
    const reset = (acc)=> data;
    
    const starters$ = Observable.merge(
        start$.mapTo(1000),
        half$.mapTo(500),
        quarter$.mapTo(250)
    );
    
    const intervalActions = (time)=> Observable.merge(
        Observable.interval(time)
            .takeUntil(stop$).mapTo(inc),
        reset$.mapTo(reset)
    );
    
    const timer$ = starters$
        .switchMap(intervalActions)
        .startWith(data)
        .scan((acc, curr)=> curr(acc))
    
    
    Observable.combineLatest(
        timer$,
        input$,
        (timer, input)=> ({count: timer.count, text: input})
    )
        .filter((data)=> data.count === parseInt(data.text))
        .subscribe(
            (x)=> console.log(x),
            err=> console.log(err),
            ()=> console.log('complete')
        );
  • 相关阅读:
    Centos7 安装RabbitMQ 3.6.1
    面向对象编程(类的绑定方法与非绑定方法)
    面向对象编程(封装、封装的意义、封装与扩展性、@property)
    函数式编程(__slots__)
    面向对象编程(实例属性、类属性)
    面向对象编程(获取对象信息)
    面向对象编程(继承、多态)
    函数式编程(访问限制)
    面向对象编程(类与实例)
    面向对象编程(基础简介)
  • 原文地址:https://www.cnblogs.com/Answer1215/p/5265924.html
Copyright © 2011-2022 走看看