如何获得“当前"订阅时观察者的价值 [英] How to get the "current" value of an Observer at subscribe-time

查看:48
本文介绍了如何获得“当前"订阅时观察者的价值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很难理解 RxJs 的一个特定部分:当您订阅 Observable 时,您只会订阅来自该 Stream 的任何未来事件.与 Promises 相比,如果 Promise 已解决,无论何时调用 then(),您都会获得该值.

I'm having a hard time grokking one particular part of RxJs: when you subscribe to an Observable, you're only subscribing to any future events from that Stream. Compare to Promises, where, if the promise has been resolved, you will get that value no matter when you call then().

这是一个代码示例:

var subject = new Rx.Subject();

subject.onNext('old value');
subject.onNext('before subscription');

subject.subscribe(function(val) {
  document.write(val);
});

subject.onNext('after subscription');

<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/2.3.24/rx.all.js"></script>

我希望看到订阅前"和订阅后"都打印出来,尽管对我来说旧值"会被删除是有道理的.但似乎 RxJs 不能那样工作(仅打印订阅后").我怎样才能得到我想要的结果?

I would expect to see both "before subscription" and "after subscription" printed, although it makes sense to me that "old value" would get dropped. But it seems that RxJs doesn't work that way (only "after subscription" is printed). How can I get the result I'm after?

推荐答案

Rx 提供这两种行为(以及其他行为).

Rx offers both behaviors (as well as others).

可用的 不同的 Rx 主题 可以让您探索可观察对象的不同行为方式:

The different Rx Subjects available can let you explore the different ways observables can behave:

  • Rx.Subject 是最基本的即发即弃类型——如果您在事件发生时没有订阅,那么您就看不到它.

  • the Rx.Subject is the most basic fire-and-forget variety -- if you were not subscribed when the event happened, then you do not see it.

使用 new Rx.BehaviorSubject(undefined) 而不是 Subject,你会得到你想要的行为,因为一个 BehaviorSubject 代表一个可以改变的值"

Use new Rx.BehaviorSubject(undefined) instead of Subject and you get the behavior you were looking for, since a BehaviorSubject represents a "value that can change"

使用 new Rx.ReplaySubject(5) 订阅后,您将立即获得 5 个最新值

Use new Rx.ReplaySubject(5) and you'll get the 5 most recent values as soon as you subscribe

使用 new Rx.AsyncSubject() 并且在 observable 完成 之前您将一无所获,此时您将获得最终值(并继续获得如果您再次订阅,则为最终值).这是 Promises 真正的 Rx 模拟,因为它在解析"(即完成)之前不会产生任何内容,然后总是将值提供给订阅的任何人.

Use new Rx.AsyncSubject() and you will get nothing until the observable completes at which time you will get the final value (and continue to get the final value if you subscribe again). This is the true Rx analog of Promises, since it produces nothing until it "resolves" (i.e. completes), and afterwards always gives the value to anyone that subscribes.

这篇关于如何获得“当前"订阅时观察者的价值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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