我正在为我的应用程序制作启动画面。我希望它在进入主屏幕之前至少持续N秒。
我有一个Rx变量myObservable
,它从服务器或本地缓存返回数据。如何在至少N秒内强制myObservable
完成?
myObservable
// .doStuff to make it last at least N seconds
.subscribe(...)
您可以使用forkJoin
等待两个Observable完成:
Observable.forkJoin(myObservable, Observable.timer(N), data => data)
.subscribe(...);
对于没有不推荐使用的结果选择器函数的RxJS 6:
forkJoin(myObservable, Observable.timer(N)).pipe(
map(([data]) => data),
)
.subscribe(...);
编辑:如评论中所述,只有一个参数的Observable.timer(N)
将在发出一个项目后完成,因此不需要使用take(1)
。
角度7+ forkjoin
的例子
我喜欢在我的开发系统上建立更长的延迟,因为我认为生产会变慢。 Observable.timer
似乎不再可用,但你可以直接使用timer
。
forkJoin(
// any observable such as your service that handles server coms
myObservable,
// or http will work like this
// this.http.get( this.url ),
// tune values for your app so very quick loads don't look strange
timer( environment.production ? 133 : 667 ),
).subscribe( ( response: any ) => {
// since we aren't remapping the response you could have multiple
// and access them in order as an array
this.dataset = response[0] || [];
// the delay is only really useful if some visual state is changing once loaded
this.loading = false;
});