skip to Main Content

Says, I have an api call that take an input since which is Unix timestamp.

  fetchData = (since?) => {
    const now = Math.floor(Date.now() / 1000); // Current Unix timestamp in seconds
    if (since) {
        //handle logic
        console.log(since)
    }
    return of({ since: now });
  };

Now I want to make an infinite loop that in each call, the input value to fetchData is the return value from the previous call. I tried with this code:

fetchData().pipe(
    expand((response: any) => {
      const { since } = response;
      return fetchData(since);
    }),
    delay(3000),
    repeat(),
  );

I don’t know why console.log kept giving me the same value. What have I done wrong here?

2

Answers


  1. You can use interval to create the infinite loop and then switch to the inner fetchData using switchMap to get the desired result.

    import './style.css';
    
    import { interval, of, switchMap } from 'rxjs';
    
    const fetchData = (since: any = null) => {
      const now = Math.floor(Date.now() / 1000); // Current Unix timestamp in seconds
      if (since) {
        //handle logic
        console.log(since);
      }
      return of({ since: now });
    };
    
    interval(3000)
      .pipe(switchMap(() => fetchData()))
      .subscribe(console.log);
    

    Stackblitz Demo

    Login or Signup to reply.
  2. You can do it like this:

    import { repeat, of, delay } from 'rxjs';
    
    const someInputValue = 5;
    
    const fetchData = (since: any = null) => {
    const now = Math.floor(Date.now() / 1000); // Current Unix timestamp in seconds
      if (since) {
        //handle logic
        console.log(since);
      }
      return of({ since: now });
    };
    
    const delayed = fetchData(someInputValue).pipe(delay(3000));
    const repeated = delayed.pipe(repeat());
    
    repeated.subscribe(console.log);
    

    Stackblitz Demo

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search