Reputation: 6596
I am aware of Observable.Never()
as a way to create a sequence that never completes, but is there an extension/clean process for creating an observable that produces a single value and then never completes? Do i go with Observable.Create(...)
? Observable.Concat(Observable.Return(onlyValue), Observable.Never<T>())
? Or is there something built in or more "RXy" than this?
Upvotes: 18
Views: 8882
Reputation: 1176
This can be done even simpler use:
Observable.Return(whatever);
Upvotes: 8
Reputation: 29776
Here's a generic utility method to do it in one go. A version of StartWith
that can be invoked without a source sequence, removing the need for Never
. Might make your code more readable if you use the construct a lot.
public partial class ObservableEx
{
public static IObservable<TValue> StartWith<TValue>(TValue value)
{
return Observable.Create<TValue>(o =>
{
o.OnNext(value);
return Disposable.Empty;
});
}
}
Upvotes: 3
Reputation: 74654
For completeness, here's the Create version:
Observable.Create<int>(subj => {
// Anyone who subscribes immediately gets a constant value
subj.OnNext(4);
// We don't have to clean anything up on Unsubscribe
// or dispose a source subscription
return Disposable.Empty;
});
Upvotes: 2
Reputation: 39182
For your specific question, a simple choice is to use ‛Never‛ and ‛StartWith‛:
Observable.Never<int>().StartWith(5)
But for the more general case of "I have an observable sequence that will produce some results and eventually complete and I want to change it so it does not complete" (of which your question is a special case), your Concat idea is the way to do it
source.Concat(Observable.Never<int>());
or
Observable.Concat(source, Observable.Never<int>());
Upvotes: 25
Reputation: 6596
Observable.Concat(Observable.Return(onlyValue), Observable.Never<T>())
seems to be sound. I was probably overthinking this anyway.
Upvotes: 9