Reputation: 3975
I have an endpoint(initiate$
) that I hit and it returns a queueId
, with that queueId
I hit another endpoint until that endpoint returns the status of ready. I have some code that works but it calls both endpoints continuously. I know why it calls both but I can't figure out how to best separate the call to just hit the second endpoint(status$
) one on subsequent calls.
RxJs: "^6.3.3"
downloadTransactionList() {
const initiate$ = this.exampleService.startListExport(userId, filter);
const status$ = this.exampleService.pollListExport(initiate$);
const polling$ = timer(0, 10000).pipe(
mergeMap(() => status$),
takeWhile(resp => resp.status !== 'ready')
);
initiate$.pipe(mergeMap(() => polling$)).subscribe(r => console.log(r));
}
Upvotes: 1
Views: 215
Reputation: 3724
If I have understood you correctly, you want that initially, a call to get a queue id is done once, and afterwords, a poller is initiated to poll for data, until the returned status is ready correct?
Try the following
downloadTransactionList() {
// This calls startListExport to get the queue id
this.exampleService.startListExport(userId, filter).subscribe((queueId:string) => {
// When it has successfully returned, initiate the poller
let timerSubscription:Subscription = timer(0, 10000).pipe(switchMap(() => {
// Assuming this returns an observable with the status
return this.exampleService.pollListExport(queueId);
})).subscribe((data:myType) => {
// DO something with your data
// Unsubscribe to stop the poller when criteria is met
if (data.status === 'ready') {
timerSubscription.unsubscribe();
}
})
});
}
Upvotes: 0
Reputation: 11000
Use a shareReplay()
operator. It multicasts source observable via ReplaySubject (in other words - ReplaySubject subscribes to the source and broadcasts it's last value to future observers).
this.exampleService.startListExport(userId, filter).pipe(shareReplay())
For the reference, here is a DEMO
Upvotes: 1