RxJS publishReplay与publishLast [英] RxJS publishReplay vs publishLast

查看:127
本文介绍了RxJS publishReplay与publishLast的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在Angular应用程序中实现缓存HTTP结果。据我所知,以下代码都有效,但我需要知道他们是否正在做完全相同的事情,或者我错过了一些重要的事情?

I am implementing caching HTTP results in Angular application. From what I know both of the following code works, but I need to know if they are doing exactly the same thing, or I am missing something important?

publishLast

getPosts() {
    if( !this.posts$ ) {
      this.posts$ = this.http.get('api').publishLast().refCount();
      return this.posts$;
    }

    return this.posts$;
  }

publishReplay

getPosts() {
  if( !this.posts$ ) {
    this.posts$ = this.http.get('api').publishReplay(1).refCount();
       return this.posts$;
  }

  return this.posts$;
}


推荐答案

publishLast 共享(顾名思义)最后发布值 - 只能在流完成时确定。

publishLast shares (as the name suggests) the last emitted value - which can only be determined when the stream completes.

publishReplay(1)分享最新发出的值,这是在任何发射后完成的。

publishReplay(1) shares the latest emitted value, which is done after any emission.

this.http.get(...)的情况下行为是相同的,因为流将在收到结果后完成,因此最后最新值是相同的。

In the case of this.http.get(...) the behavior is the same, because the stream will complete after the result was received, thus the last and the latest value are the same thing.

对于发出多个值但在发出此值后不立即完成的流,您会得到不同的结果。

You will have a different result though for streams that emit more than one value or that do not complete immediately after the emission of this value.

这篇关于RxJS publishReplay与publishLast的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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