[英]Rx.Net Using Observable.Create instead of Subject
I have code that uses a subject to create an observable. 我有使用主题创建可观察对象的代码。 I'm able to pass in a value to the observable stream using subject.onNext(value). 我可以使用subject.onNext(value)将值传递给可观察的流。 The problem is if I subscribe to that observable after a value was passed in, I would like to still get that value. 问题是,如果在值传递后我订阅了该可观察值,则我仍希望获得该值。 From what I can tell, subjects don't hold onto value, they just pass them along like an event. 据我所知,主体没有抓住价值,他们只是像事件一样传递它们。 So how do I change this code from using subject, to using an Observable. 因此,如何将这段代码从使用subject更改为使用Observable。
private readonly Subject<int> _valueSubject = new Subject<int>();
public IObservable<int> ValueObservable => _valueSubject ;
public void SetValue(int valuePassedIn)
{
_valueSubject.OnNext(valuePassedIn);
}
Edit: Found out you can get latest values using BehaviorSubject, but would still like to know how to use Observable.Create instead of Subject in a scenario like this. 编辑:发现您可以使用BehaviorSubject获取最新值,但仍然想知道如何在这种情况下使用Observable.Create而不是Subject。
Assuming that you don't need to call the OnNext directly, a cold observable might be what you want: 假设您不需要直接调用OnNext,那么您可能想要一个冷的可观察对象:
IObservable<int> coldObservable = Observable.Create<int>(obs =>
{
obs.OnNext(1);
obs.OnNext(2);
obs.OnNext(3);
obs.OnCompleted();
return () => { };
});
Otherwise a ReplaySubject will allow you to keep a sized buffer of values that will be emitted as each observer subscribes. 否则,ReplaySubject将允许您保留一个大小可变的值缓冲区,该值将在每个观察者订阅时发出。 Not exactly the same as remembering all values I realize but this would not be a good idea anyway due to memory usage. 与记住我意识到的所有值并不完全相同,但是由于内存使用情况,这绝对不是一个好主意。 Might be closer than the single value BehaviourSubject provides. 可能比BehaviourSubject提供的单个值更近。
The following will allow 2 values to be available to new subscribers: 下面将允许2个值可用于新订户:
ISubject<int> replaySubject = new ReplaySubject<int>(2);
IObservable<int> observable;
[TestMethod]
public void TestMethod()
{
observable = replaySubject;
replaySubject.OnNext(1);
replaySubject.OnNext(2);
replaySubject.OnNext(3);
replaySubject.OnNext(4);
replaySubject.OnNext(5);
observable.Subscribe(OnValue);
}
Output: 输出:
Observed value:4 Observed value:5 观察值:4观察值:5
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.