javascript 如何在订阅时获取观察者的“当前”值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28311118/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 08:45:29  来源:igfitidea点击:

How to get the "current" value of an Observer at subscribe-time

javascriptrxjs

提问by DallonF

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

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

Here's a code example:

这是一个代码示例:

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>

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?

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

回答by Brandon

Rx offers both behaviors (as well as others).

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

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

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

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

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

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

  • Use new Rx.AsyncSubject()and you will get nothing until the observable completesat 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.

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

  • 使用new Rx.BehaviorSubject(undefined)而不是,Subject你会得到你正在寻找的行为,因为 aBehaviorSubject代表一个“可以改变的值”

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

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