Observable Continue calling the API and changing the parameters based on the condition

I read the Rx.js repeat Documentation in an attempt to figure out how I can continue the api call based on the response I receive from API. I call APIwhich can send back 2krecords at a time. The API will send me the value to send, so that I can continue to receive the records until they return the value made.

So, the flow goes as follows:

  • Make a GETrequest parameter request reqMode='':
  • get the answer with the last array containing reqModewith valueor done.
  • If I receive value, then I need to make the same request, but send a parameter reqModewith a value.
  • If I receive done, I will stop and return all records from the time of the first call.

I get the first set of values ​​when subscribing normally, but that would be my attempt after reading the documents, but that doesn't make sense:

getRecords(){
    let url = this.url + 'reqMode=';
    return this.http.get(url)
            .doWhile() //What would I do here
}

When trying to do .doWhilewith an observable, that is a type Observable<response>. I am looking for any alternative using Observables for what I need to do.

+4
source share
2 answers

, repeat() . , HTTP- . repeat() , .

concatMap() , reqMode eqaul "done":

-: http://plnkr.co/edit/w0DdepslTaKrLSB3aIkA

import {Observable, Subject} from 'rxjs';

const result = new Subject();
const closeBuffer = new Subject();
const buffer = result.buffer(closeBuffer.asObservable());

function sendHttpRequest(reqMode) {
  return Observable.of('{"reqMode":' + reqMode + '}')
    .map(response => JSON.parse(response))
    .concatMap(data => {
      console.log('HTTP Response:', data);
      // Add data to the buffer of results
      result.next(data);

      if (data.reqMode == 'done') {
        // Return an empty value wrapped as an Observable so concatMap can work
        // with it and emit onNext when it completes (which is immediately
        // thanks to the `.of()` operator).
        return Observable.of(null);
      } else {
        // Simulate that the next call returns 'done'
        return sendHttpRequest('"done"');

        // Uncomment this for real usage
        //return sendHttpRequest(data.reqMode);
      }
    });
}

// Subscribe to the buffer where I'll receive the value.
buffer.subscribe(val => console.log('Next: ', val));

// Simulate HTTP request with reqMode = 42
sendHttpRequest(42).subscribe(() => {
  console.log('done');
  // Emit values from the buffer.
  closeBuffer.next(null);
  closeBuffer.complete();
});

of() , . Subject , buffer(). , ( , buffer, ).

:

HTTP Response: Object {reqMode: 42}
HTTP Response: Object {reqMode: "done"}
Next:  [Object, Object]

. : Angular 2 + rxjs - , HTTP-

+4

, , , wrapping observer .repeat().

app.component.ts

, http-, , . , 5.

, " " .

, !

+2

Source: https://habr.com/ru/post/1656404/


All Articles