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')
        );
  • 相关阅读:
    Mysql第八天 分区与分表
    ios—项目开发需求文档
    spark资料下载
    网络爬虫:使用多线程爬取网页链接
    调用微信高级群发接口--视频群发接口出问题(微信官方文档错误纠正)
    享元模式
    在JAVA中怎样跳出当前的多重嵌套循环?
    获取个人借阅信息---图书馆client
    IOS 以随意点为圆心 旋转UIView
    ESP8266学习笔记4:ESP8266的SmartConfig
  • 原文地址:https://www.cnblogs.com/Answer1215/p/5265924.html
Copyright © 2011-2022 走看看