zoukankan      html  css  js  c++  java
  • [Reactive Programming] Async requests and responses in RxJS

    We will learn how to perform network requests to a backend using RxJS Observables.

    A example of basic jquery request:

    console.clear();
    var requestStream = Rx.Observable.just('https://api.github.com/users');
    
    //Current requestStream is just a stream 
    //We need to subscribe it to make it work
    requestStream.subscribe(url => {
      
      //Preform a serve reqest by jQuery
      jQuery.getJSON(url).done( res => {
        console.log(res);
      })
    });

    But it not make so many sence we use jQuery to handle the promise since we already using RxJS:

    console.clear();
    var requestStream = Rx.Observable.just('https://api.github.com/users');
    
    //Current requestStream is just a stream 
    //We need to subscribe it to make it work
    requestStream.subscribe( url => {
      
      //Using Rx.Observable.fromPromise() to handle the response
      //Since jQuery.getJSON(url) return a promise
      //there we put into the fromPromise() function
      var responseStream = Rx.Observable.fromPromise(jQuery.getJSON(url));
      
      //Then subscribe the responseStream 
      responseStream.subscribe( res => {
        console.log(res);
      });
    });

    We see that we can accomplish with promise we also can do in Observable. And the main problem for promise is that promise only even yield a single value. But observalbe can have mult events.

    But soon we find we subscribe an stream inside another subscribe, this is what we don't have to do, normal way to avoid this is using flatMap().

    Here we do flagMap() but not map() is because inside map() a observable and return another observable then we got an observable of observable. 

    console.clear();
    var requestStream = Rx.Observable.just('https://api.github.com/users');
    var responseStream = requestStream
      .flatMap( url => Rx.Observable.fromPromise(jQuery.getJSON(url)));
    
    responseStream.subscribe( res => console.log(res));

    Now we have only one subscribe.

  • 相关阅读:
    常用的DOCS命令
    [51NOD1126]求递推序列的第n项(矩阵快速幂)
    [HDOJ2830]Matrix Swapping II(胡搞)
    [每天一道A+B]签到检测程序
    [HIHO1260]String Problem I(trie树)
    [HIHO1300]展胜地的鲤鱼旗(栈,dp)
    [HIHO1299]打折机票(线段树)
    [51NOD1087]1 10 100 1000(规律,二分)
    [POJ2002]Squares(计算几何,二分)
    [HDOJ1015]Safecracker(DFS, 组合数学)
  • 原文地址:https://www.cnblogs.com/Answer1215/p/4857602.html
Copyright © 2011-2022 走看看