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?
I tried this:
fakeObservable = Observable.create(obs => {
setTimeout(() => {
obs.next([1, 2, 3]);
obs.complete();
}, 100);
});
But it doesn't seem to work.
This question is related to
angular
typescript
observable
import * as Rx from 'rxjs/Rx';
We should add the above import to make the blow code to work
Let obs = Rx.Observable
.interval(1000).take(3);
obs.subscribe(value => console.log('Subscriber: ' + value));
It's little late to answer ... but just in case may be someone return to this question looking for an answer
'delay' is property(function) of an Observable
fakeObservable = Observable.create(obs => {
obs.next([1, 2, 3]);
obs.complete();
}).delay(3000);
This worked for me ...
In RxJS 5+ you can do it like this
import { Observable } from "rxjs/Observable";
import { of } from "rxjs/observable/of";
import { delay } from "rxjs/operators";
fakeObservable = of('dummy').pipe(delay(5000));
In RxJS 6+
import { of } from "rxjs";
import { delay } from "rxjs/operators";
fakeObservable = of('dummy').pipe(delay(5000));
If you want to delay each emitted value try
from([1, 2, 3]).pipe(concatMap(item => of(item).pipe(delay(1000))));
What you want is a timer:
// RxJS v6+
import { timer } from 'rxjs';
//emit [1, 2, 3] after 1 second.
const source = timer(1000).map(([1, 2, 3]);
//output: [1, 2, 3]
const subscribe = source.subscribe(val => console.log(val));
Source: Stackoverflow.com