0

I am recently learning rxjs. I am trying to obtain data over a http stream (Asynchronously, without closing the stream after a single response is received. I want multiple response from a single http request over time). So the UI code for rxjs would be something like this,

this.http.get('https://...').subscribe(value => {
     ...
    });

However i dont know how to send data asynchronously through http response from backend. The http response waits for the entire json to be completed and it ends up sending the entire data in a single response. I don't want that. How to code the backend to send a json data as soon as it is available instead of waiting for all data to be obtained and sending as [{..},{..},{..}....]?

Alakay1197
  • 47
  • 4

1 Answers1

0

Have a response object with a flag to indicate if there is more data.

interface Response {
  payload: Payload,
  complete: boolean
}

Then your service can make a request to the server which sends a response as soon as it has some data with complete false, your service keeps pooling the server until the server responds with complete true.

const { of } = rxjs;
const { switchMap, map } = rxjs.operators;

let i = 0;

const http = url => of({ payload: [i++], complete: i === 5 ? true : false });

const poll = () => http('url').pipe(
  switchMap(response => response.complete ? of(response) : poll().pipe(
    map(res => ({ payload: [...response.payload, ...res.payload], complete: res.complete }))
  ))
);

poll().subscribe(response => { console.log(response); });
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/6.5.3/rxjs.umd.min.js"></script>
Adrian Brand
  • 20,384
  • 4
  • 39
  • 60