如何延迟创建可观察对象 [英] How can I create an observable with a delay

查看:76
本文介绍了如何延迟创建可观察对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

出于测试目的,我正在创建Observable对象,用Http替换实际http调用将返回的可观察对象.

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?

我尝试过:

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

但这似乎不起作用.

推荐答案

使用以下导入:

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

尝试一下:

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

更新:RXJS 6

以上解决方案在RXJS的较新版本(例如,角度版本)中不再有效.

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

所以这种情况是我有一系列要与API一起检查的项目.该API只接受一个项目,并且我不想一次发送所有请求来终止该API.因此,我需要定时释放Observable流上的项目,并且之间要稍加延迟.

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.

使用以下导入:

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

然后使用以下代码:

const myArray = [1,2,3,4];

from(myArray).pipe(
        concatMap( item => of(item).pipe ( delay( 1000 ) ))
    ).subscribe ( timedItem => {
        console.log(timedItem)
    });

它基本上为数组中的每个项目创建一个新的延迟" Observable.可能还有很多其他方法,但这对我来说很好用,并且符合新的" RXJS格式.

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.

这篇关于如何延迟创建可观察对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆