zoukankan      html  css  js  c++  java
  • [RxJS] Starting a Stream with SwitchMap & switchMapTo

    From an event map to another event we can use switchMap(), switchMap() accept an function which return an obervable.

    The following code: When you click the button, it will start a interval to console out the count...

    const Observable = Rx.Observable;
    
    const startButton = document.querySelector('#start');
    
    
    const start$ = Rx.Observable.fromEvent(startButton, 'click');
    const interval$ = Observable.interval(400);
    
    const startInterval$ = start$.switchMap( () => {
      return interval$;
    });
    
    startInterval$.subscribe( (x) => {
       console.log(x);
    });

    So the start$ switch map to a interval$ to avoid writting the nested subscribe function.

    switchMap() actually is pretty useful when dealing with http event stream, it can help to cancel the previous http call.

    switchMapTo(): which accept an observable:

    /*
    const startInterval$ = start$.switchMap( () => {
      return interval$;
    });*/
    
    const startInterval$ = start$.switchMapTo( interval$ );

    Tow pieces of code, works the same way.

  • 相关阅读:
    [POJ1724]ROADS
    表达式求值
    [NOIp2017提高组]奶酪(BFS)
    [NOIp2012提高组]Vigenère 密码
    [NOIp2012提高组]国王游戏
    [POJ1321]棋盘问题
    [POJ3009]Curling2.0
    垃圾陷阱
    2019CSP day1t2 括号树
    2019CSP游记
  • 原文地址:https://www.cnblogs.com/Answer1215/p/5252595.html
Copyright © 2011-2022 走看看