Search code examples
angulartypescriptobservable

How can I create an observable with a delay


Question

For testing purposes, I'm creating Observable objects that replace the observable that would be returned by an actual http call with Http.

My observable is created with the following code:

fakeObservable = Observable.create(obs => {
  obs.next([1, 2, 3]);
  obs.complete();
});

The thing is, this observable emits immediatly. Is there a way to add a custom delay to its emission?


Track

I tried this:

fakeObservable = Observable.create(obs => {
  setTimeout(() => {
    obs.next([1, 2, 3]);
    obs.complete();
  }, 100);
});

But it doesn't seem to work.


Solution

  • Using the following imports:

    import {Observable} from 'rxjs/Observable';
    import 'rxjs/add/observable/of';
    import 'rxjs/add/operator/delay';
    

    Try this:

    let fakeResponse = [1,2,3];
    let delayedObservable = Observable.of(fakeResponse).delay(5000);
    delayedObservable.subscribe(data => console.log(data));
    

    UPDATE: RXJS 6

    The above solution doesn't really work anymore in newer versions of RXJS (and of angular for example).

    So the scenario is that I have an array of items to check with an API with. The API only accepts a single item, and I do not want to kill the API by sending all requests at once. So I need a timed release of items on the Observable stream with a small delay in between.

    Use the following imports:

    import { from, of } from 'rxjs';
    import { delay } from 'rxjs/internal/operators';
    import { concatMap } from 'rxjs/internal/operators';
    

    Then use the following code:

    const myArray = [1,2,3,4];
    
    from(myArray).pipe(
            concatMap( item => of(item).pipe ( delay( 1000 ) ))
        ).subscribe ( timedItem => {
            console.log(timedItem)
        });
    

    It basically creates a new 'delayed' Observable for every item in your array. There are probably many other ways of doing it, but this worked fine for me, and complies with the 'new' RXJS format.