zoukankan      html  css  js  c++  java
  • [RxJS] How To get the results of two HTTP requests made in sequence

    switchMap can chain two HTTP requests together, creating one request based on the results of the first request.

    But the result observable did not have the data of the first request, instead it only had access to the data of the second HTTP request.

    If we would like to have both the data of the first HTTP request and deliver it together with the data of the second request, we could use a selector function (notice the second argument passed to switchMap):

    sequentialRequests() {
    
    const sequence$ = this.http.get<Course>(
                '/courses/-KgVwEBq5wbFnjj7O8Fp.json')
        .switchMap(course => {
            course.description+= ' - TEST ';
            return this.http.put('/courses/-KgVwEBq5wbFnjj7O8Fp.json', course)
        },
        (firstHTTPResult, secondHTTPResult)  => 
                   [firstHTTPResult, secondHTTPResult]);
    
    sequence$.subscribe(
        values => console.log("result observable ", values) 
    );
        
    }

    Other example:

    //emit immediately, then every 5s
    const source = Rx.Observable.timer(0, 5000);
    //switch to new inner observable when source emits, invoke project function and emit values
    const example = source.switchMap(() => Rx.Observable.interval(2000), (outerValue, innerValue, outerIndex, innerIndex) => ({outerValue, innerValue, outerIndex, innerIndex}));
    /*
        Output:
        {outerValue: 0, innerValue: 0, outerIndex: 0, innerIndex: 0}
        {outerValue: 0, innerValue: 1, outerIndex: 0, innerIndex: 1}
        {outerValue: 1, innerValue: 0, outerIndex: 1, innerIndex: 0}
        {outerValue: 1, innerValue: 1, outerIndex: 1, innerIndex: 1}
    */
    const subscribe = example.subscribe(val => console.log(val));
  • 相关阅读:
    A20的板子笔记
    RT-Thread信号量的基本操作
    RT-Thread的线程间同步
    RT-Thread多线程导致的临界区问题
    RT-Thread的CPU使用率计算
    RT-Thread 线程的让出
    车牌识别LPR(八)-- 字符识别
    车牌识别LPR(七)-- 字符特征
    车牌识别LPR(六)-- 字符分割
    车牌识别LPR(五)-- 一种车牌定位法
  • 原文地址:https://www.cnblogs.com/Answer1215/p/7418632.html
Copyright © 2011-2022 走看看