1

I have a function that call a client and get data back and returns it:

       const remoteConnection = await
          this.client.connectionStatus(chassi, number, language) || [];
        return {
          data: remoteConnection as RemoteInfo,
          read: new Date()
        };

The response will be in this form:

 {
   connectionStatus: "",
   online: ""
 }

connectionStatus can have three states:

'disconnected'
'pending'
'connected'

I want to call my API and send the data. IF 'connectionStatus' is 'pending', I want to call the API every 5s to check if it changes to 'connected'. In that case, I want to return the data again with the new values.

In a nutshell:

Make API call and return the data. If 'connectionStatus' in the return data is equal to 'pending', make a new call every 5s to check if 'connectionStatus' is equal to 'connected'. If true, return data again.

How to do it?

Yatinj Sutariya
  • 506
  • 5
  • 15

2 Answers2

2

You could use timer to trigger making your api call and use takeUntil to stop whenever the status meets your condition:

const data$ = timer(0, 5000).pipe(
  concatMap(() => client.connectionStatus()),
  takeWhile(resp => resp.connectionStatus === 'pending', true),
  map(data => ({ data, read: new Date() }))
);

Here's the flow:

  • timer emits immediately, then every 5 seconds
  • concatMap calls your method and emits the result of the promise
  • takeWhile causes the stream to complete when the condition is met
  • map simply transforms the RemoteInfo response to your desired shape

Simply subscribe to this observable to trigger execution and receive emissions:

data$.subscribe();

Here's a StackBlitz sample.

If the observable will have multiple subscribers, you may wish to prevent multiple separate calls to your api by leveraging the share operator, which will cause all subscribers to share the same subscription:

const data$ = timer(0, 5000).pipe(
  concatMap(() => client.connectionStatus()),
  takeWhile(resp => resp.connectionStatus === 'pending', true),
  map(data => ({ data, read: new Date() })),
  share() // <---
);
BizzyBob
  • 12,309
  • 4
  • 27
  • 51
1

This question shows how to run a function every 5 seconds:

var intervalId = window.setInterval(function(){ /// call your function here }, 5000);

In this case, you would run this function while connectionStatus = pending

var intervalId = window.setInterval(function() {
  if (connectionStatus != pending) {
    clearInterval(intervalId); // stop the loop
    return data;
  } 
}, 5000);
Sour_Tooth
  • 125
  • 9