You could simply treat the Task like any other sequence, and just chain it into the query
Start().ToObservable()
.SelectMany(_=>MyObservable)
.Finally(Stop)
As a separate note, I would encourage you to avoid crafting API's that have methods that take the format IDisposable Subscribe(IObserver<MyType> observer)
. This takes away the power of Rx from your consumers. Instead, just expose the IObservable<T>
, as it has the Subscribe
method already. Now your consumer can chain your sequence, compose it, choose the correct concurrency/threading model (with ObserveOn
/SubscribeOn
), and apply their Error handling requirements.
Also as a last note, it is a bit strange to publish-refcount a sequence that is the result of a method call. It is even more strange to publish-refcount when your method only allows the consumer to provide one consumer. Assuming you change your method signature to the recommended/standard approach, then I would also suggest that you either remove the Publish().Refcount()
code as it would highly unlikely for the consumer to cached the result and reuse it, v.s. recalling the method. Or you can keep the method (even better change it to a property) and then you internally cache the published sequence.
public class MyServiceThing
{
private readonly IObservable<MyType> _myObservable;
public MyServiceThing()
{
_myObservable = Start().ToObservable()
.SelectMany(_=>/*The thing that defines your observable sequence...*/)
.Finally(Stop)
.Publish().RefCount();
}
public IObservable<MyType> MyObservable()
{
return _myObservable;
}
//OR
//public IObservable<MyType> MyObservable() { get { return _myObservable; } }
private async Task Start() {}
private async Task Stop() {}
}