Rx :强制 observable 至少需要 N 秒才能完成

Rx : Force observable to take at least N seconds to complete

我正在为我的应用制作启动画面。我希望它在进入主屏幕之前至少持续 N 秒。

我有一个 Rx 变量 myObservable returns 来自服务器或本地缓存的数据。我如何强制 myObservable 至少 N 秒 内完成?

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)

Angular forkjoin

的 7+ 个示例

我喜欢在我的开发系统上建立一个更高的延迟,因为我认为生产会更慢。 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;

});