问题
I am trying to inject an initial value into an RX stream using the StartWith
method:
public async Task<IObservable<Price>) Stream(Instrument instrumentDetails)
{
var initialPrice = await _svc.GetSomeInitialPrice();
var stream = _priceObserver.Stream
.Where(o => o.Symbol == instrumentDetails.Symbol)
.Select(o => GetPrice(o, instrumentDetails));
stream.StartWith(initialPrice);
return stream;
}
however, the method is async due to the call to get the initial value. and it needs to be async all the way through this call stack anyway
I am finding the value is never added to the start. I just get the rest of the stream
if I await
the StartWith
method, it never returns
any ideas what I'm doing wrong
回答1:
The methods on the IObservable
don't modify the underlying object - they return a new one. stream.StartWith(initialPrice)
returns a new observable which you ignore, it doesn't do anything to stream
.
You should write it like this:
stream = stream.StartWith(initialPrice);
Or:
var stream = _priceObserver.Stream
.Where(o => o.Symbol == instrumentDetails.Symbol)
.Select(o => GetPrice(o, instrumentDetails))
.StartWith(initialPrice);
Side note: if you await an observable, it will wait until the observable is complete, i.e. when it emits all its values and calls its OnComplete
method. You should usually await an observable, which you know will emit only 1 value and then complete (e.g. a request to a remote server), because awaiting it will return only the last emitted value. So if your stream
is expected to continuously emit values, it makes no sense to await it.
回答2:
You're better off avoiding mixing of Task<>
and Observable<>
like you're doing. If you can, just stick with IObservable<>
.
In your case it's pretty easy.
Just try this:
public IObservable<Price> Stream(Instrument instrumentDetails)
=>
Observable
.FromAsync(() => _svc.GetSomeInitialPrice())
.SelectMany(x =>
_priceObserver
.Stream
.Where(o => o.Symbol == instrumentDetails.Symbol)
.Select(o => GetPrice(o, instrumentDetails))
.StartWith(x));
I've tested this with a basic bit of code and it works just fine. It also ensures that new subscribers will any new values that _svc.GetSomeInitialPrice()
might produce over time.
来源:https://stackoverflow.com/questions/60339649/rx-startwith-in-async-method-not-applying-the-starting-value