简体   繁体   中英

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). 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.

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.

Assuming that you don't need to call the OnNext directly, a cold observable might be what you want:

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. 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.

The following will allow 2 values to be available to new subscribers:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM