Question

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?

Was it helpful?

Solution

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>());

OTHER TIPS

Observable.Concat(Observable.Return(onlyValue), Observable.Never<T>()) seems to be sound. I was probably overthinking this anyway.

This can be done even simpler use:

Observable.Return(whatever);

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;
        });
    }
}

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;
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top