问题
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.
回答1:
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.
回答2:
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));
回答3:
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 ...
回答4:
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));
回答5:
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));
来源:https://stackoverflow.com/questions/42413969/how-can-i-create-an-observable-with-a-delay