I wanted to check that an IObservable I had created was respecting the courtesy of "Once I've completed, I'll unsubscribe you". At first blush it looked like something was wrong with my code. But eliminating my code, and just using the Observable and Observer provided by TestScheduler, it looks like the 'unsubscription' never happens:
using Microsoft.Reactive.Testing;
using System.Reactive;
...
var ts = new TestScheduler();
var ob = ts.CreateObserver<int>();
var xs = ts.CreateColdObservable<int>(
new Recorded<Notification<int>>(1, Notification.CreateOnCompleted<int>())
);
xs.Subscribe(ob);
ts.AdvanceTo(2);
Assert.Equal(1, xs.Subscriptions.Single().Unsubscribe); //<-- Xunit no like
I originally suspected the observer, but I tried that on a variant of the code found here, and it works, so now I'm thinking that the implementation of Subscribe on the ColdObservable isn't behaving properly.
No such courtesy exists. The RX design guideines in section 4.3 suggest you can:
Assume resources are cleaned up after an OnError or OnCompleted message.
And in section 4.4 say you can:
Assume a best effort to stop all outstanding work on Unsubscribe
These guidelines ("courtesies") talk about an operator releasing it's own resources plus those of any it has acquired as soon as possible.
In your code, you aren't testing for either of these scenarios. The purpose of the Unsubscribe property on an ITestableObservable is to report when a subscription taken out by an observer was explicitly disposed, not when internal cleanup happened - but you are not storing this handle to be able to dispose it:
xs.Subscribe(ob); /* return of handle ignored here */
So you are trying to assert that you disposed the subscription you threw away, not that the observable you subscribed to cleaned up any subscription and resources it may have taken out.
If you want to see the effect of the timely resource clean up of 4.3/4.4, write an extension method like this:
public static IObservable<T> SpyResourceCleanUp<T>(
this IObservable<T> source, IScheduler scheduler)
{
return Observable.Create<T>(obs =>
{
var subscription = source.Subscribe(obs);
return new CompositeDisposable(
subscription,
Disposable.Create(() => Console.WriteLine(
"Clean up performed at " + scheduler.Now.Ticks)));
});
}
And replace your line:
xs.Subscribe(ob);
with
xs.SpyResourceCleanUp(ts).Subscribe(ob);
(Editing in some of the comments)
On your test I see immediate resource clean-up, as I would expect. And with this change your test will now pass because SpyResourceCleanUp is unsubscribing from it's parent (xs) as soon as it OnCompletes() itself in adherence to 4.3 of the guidelines.
What might not be obvious here is that Observable.Create handles calling the Dispose() method of the returned IDisposable as soon as either the subscription is disposed or OnComplete() or OnError() has been called on the observer. This is how Create helps you implement section 4.3, and why the test passes with the altered code.
Under the covers, subscriptions to the AnonymousObservable<T> : ObservableBase<T> returned by Create are wrapped by an AutoDetachObserver as you can see here.
i.e. The Disposable you return from Observable.Create isn't the one the caller gets - they get a wrapped version that will call your Dispose() either on stream termination or cancellation.
Related
I'm using the Reactive .NET extensions and I wonder about its disposal. I know in some cases it's good to dispose it like that: .TakeUntil(Observable.Timer(TimeSpan.FromMinutes(x))). I
First case
In this case, I have a timer that triggers after x seconds and then it completes and should be disposed.
public void ScheduleOrderCancellationIfNotFilled(string pair, long orderId, int waitSecondsBeforeCancel)
{
Observable.Timer(TimeSpan.FromSeconds(waitSecondsBeforeCancel))
.Do(e =>
{
var result = _client.Spot.Order.GetOrder(pair, orderId);
if (result.Success)
{
if (result.Data?.Status != OrderStatus.Filled)
{
_client.Spot.Order.CancelOrder(pair, orderId);
}
}
})
.Subscribe();
}
Second case
In this case, the timer runs on the first second and then it repeats itself on each 29 minutes. This should live until its defining class is disposed. I believe this one should be disposed with IDisposable implementation. How?
var keepAliveListenKey = Observable.Timer(TimeSpan.FromSeconds(1), TimeSpan.FromMinutes(29))
.Do(async e =>
{
await KeepAliveListenKeyAsync().ConfigureAwait(false);
})
.Subscribe();
Edit
I also want it to be using a Subject<T> which makes it easier to dispose and to reset the subscription.
For ex. Reset and Dispose observable subscriber, Reactive Extensions (#Enigmativity)
public class UploadDicomSet : ImportBaseSet
{
IDisposable subscription;
Subject<IObservable<long>> subject = new Subject<IObservable<long>>();
public UploadDicomSet()
{
subscription = subject.Switch().Subscribe(s => CheckUploadSetList(s));
subject.OnNext(Observable.Interval(TimeSpan.FromMinutes(2)));
}
void CheckUploadSetList(long interval)
{
subject.OnNext(Observable.Never<long>());
// Do other things
}
public void AddDicomFile(SharedLib.DicomFile dicomFile)
{
subject.OnNext(Observable.Interval(TimeSpan.FromMinutes(2)));
// Reset the subscription to go off in 2 minutes from now
// Do other things
}
}
In the first case it gonna be disposed automatically. It is, actually, a common way to achieve automatic subscription management and that's definitely nice and elegant way to deal with rx.
In the second case you have over-engineered. Observable.Timer(TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1)) is itself sufficient to generate a sequence of ascending longs over time. Since this stream is endless by its nature, you right - explicit subscription management is required. So it is enough to have:
var sub = Observable.Timer(TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1)).Subscribe()
...and sub.Dispose() it later.
P.S. Note that in your code you .Do async/await. Most probably that is not what you want. You want SelectMany to ensure that async operation is properly awaited and exceptions handled.
Answering your questions in the comments section:
What about disposing using Subject instead?
Well, nothing so special about it. Both IObserver<>, IObservable<> is implemented by this class such that it resembles classical .NET events (list of callbacks to be called upon some event). It does not differ in any sense with respect to your question and use-case.
May you give an example about the .Do with exception handling?
Sure. The idea is that you want translate your async/await encapsulated into some Task<T> to IObservable<T> such that is preserves both cancellation and error signals. For that .SelectMany method must be used (like SelectMany from LINQ, the same idea). So just change your .Do to .SelectMany.
Observable
.Timer(TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1))
.SelectMany(_ => Observable.FromAsync(() => /* that's the point where your Task<> becomes Observable */ myTask))
I'm confused again. Do I need IObservable<IObservable> (Select) or IObservable (SelectMany)
Most probably, you don't need switch. Why? Because it was created mainly to avoid IO race conditions, such that whenever new event is emitted, the current one (which might be in progress due to natural parallelism or asynchronous workflow) is guaranteed to be cancelled (i.e. unsubscribed). Otherwise race conditions can (and will) damage your state.
SelectMany, on the contrary, will make sure all of them are happen sequentially, in some total order they have indeed arrived. Nothing will be cancelled. You will finish (await, if you wish) current callback and then trigger the next one. Of course, such behavior can be altered by means of appropriate IScheduler, but that is another story.
Reactive Observable Subscription Disposal (#Enigmativity)
The disposable returned by the Subscribe extension methods is returned solely to allow you to manually unsubscribe from the observable before the observable naturally ends.
If the observable completes - with either OnCompleted or OnError - then the subscription is already disposed for you.
One important thing to note: the garbage collector never calls .Dispose() on observable subscriptions, so you must dispose of your subscriptions if they have not (or may not have) naturally ended before your subscription goes out of scope.
First case
Looks like I don't need to manually .Dispose() the subscription in the first case scenario because it ends naturally.
Dispose is being triggered at the end.
var xs = Observable.Create<long>(o =>
{
var d = Observable.Timer(TimeSpan.FromSeconds(5))
.Do(e =>
{
Console.WriteLine("5 seconds elapsed.");
})
.Subscribe(o);
return Disposable.Create(() =>
{
Console.WriteLine("Disposed!");
d.Dispose();
});
});
var subscription = xs.Subscribe(x => Console.WriteLine(x));
Second case
but in the second case, where it doesn't end "naturally", I should dispose it.
Dispose is not triggered unless manually disposed.
var xs = Observable.Create<long>(o =>
{
var d = Observable.Timer(TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1))
.Do(e =>
{
Console.WriteLine("Test.");
})
.Subscribe(o);
return Disposable.Create(() =>
{
Console.WriteLine("Disposed!");
d.Dispose();
});
});
var subscription = xs.Subscribe(x => Console.WriteLine(x));
Conclusion
He gave such a nice examples, it's worth seeing if you are asking yourself the same question.
Recently I stumbled upon an interesting statement by Enigmativity about the Publish and RefCount operators:
You're using the dangerous .Publish().RefCount() operator pair which creates a sequence that can't be subscribed to after it completes.
This statement seems to oppose Lee Campbell's assessment about these operators. Quoting from his book Intro to Rx:
The Publish/RefCount pair is extremely useful for taking a cold observable and sharing it as a hot observable sequence for subsequent observers.
Initially I didn't believe that Enigmativity's statement was correct, so I tried to refute it. My experiments revealed that the Publish().RefCount() can be
indeed inconsistent. Subscribing a second time to a published sequence can cause a new subscription to the source sequence, or not, depending on whether the source sequence was completed while connected. If it was completed, then it won't be resubscribed. If it was not completed, then it will be resubscribed. Here is a demonstration of this behavior:
var observable = Observable
.Create<int>(o =>
{
o.OnNext(13);
o.OnCompleted(); // Commenting this line alters the observed behavior
return Disposable.Empty;
})
.Do(x => Console.WriteLine($"Producer generated: {x}"))
.Finally(() => Console.WriteLine($"Producer finished"))
.Publish()
.RefCount()
.Do(x => Console.WriteLine($"Consumer received #{x}"))
.Finally(() => Console.WriteLine($"Consumer finished"));
observable.Subscribe().Dispose();
observable.Subscribe().Dispose();
In this example the observable is composed by three parts. First is the producing part that generates a single value and then completes. Then follows the publishing mechanism (Publish+RefCount). And finally comes the consuming part that observes the values emitted by the producer. The observable is subscribed twice. The expected behavior would be that each subscription will receive one value. But this is not what happens! Here is the output:
Producer generated: 13
Consumer received #13
Producer finished
Consumer finished
Consumer finished
(Try it on fiddle)
And here is the output if we comment the o.OnCompleted(); line. This subtle change results to a behavior that is expected and desirable:
Producer generated: 13
Consumer received #13
Producer finished
Consumer finished
Producer generated: 13
Consumer received #13
Producer finished
Consumer finished
In the first case the cold producer (the part before the Publish().RefCount()) was subscribed only once. The first consumer received the emitted value, but the second consumer received nothing (except from an OnCompleted notification). In the second case the producer was subscribed twice. Each time it generated a value, and each consumer got one value.
My question is: how can we fix this? How can we modify either the Publish operator, or the RefCount, or both, in order to make them behave always consistently and desirably? Below are the specifications of the desirable behavior:
The published sequence should propagate to its subscribers all notifications coming directly from the source sequence, and nothing else.
The published sequence should subscribe to the source sequence when its current number of subscribers increases from zero to one.
The published sequence should stay connected to the source as long as it has at least one subscriber.
The published sequence should unsubscribe from the source when its current number of subscribers becomes zero.
I am asking for either a custom PublishRefCount operator that offers the functionality described above, or for a way to achieve the desirable functionality using the built-in operators.
Btw a similar question exists, that asks why this happens. My question is about how to fix it.
Update: In retrospect, the above specification results to an unstable behavior that makes race-conditions unavoidable. There is no guarantee that two subscriptions to the published sequence will result to a single subscription to the source sequence. The source sequence may complete between the two subscriptions, causing the unsubscription of the first subscriber, causing the unsubscription of the RefCount operator, causing a new subscription to the source for the next subscriber. The behavior of the built-in .Publish().RefCount() prevents this from happening.
The moral lesson is that the .Publish().RefCount() sequence is not broken, but it's not reusable. It cannot be used reliably for multiple connect/disconnect sessions. If you want a second session, you should create a new .Publish().RefCount() sequence.
Lee does a good job explaining IConnectableObservable, but Publish isn't explained that well. It's a pretty simple animal, just hard to explain. I'll assume you understand IConnectableObservable:
If we to re-implement the zero-param Publish function simply and lazily, it would look something like this:
// For illustrative purposes only: don't use this code
public class PublishObservable<T> : IConnectableObservable<T>
{
private readonly IObservable<T> _source;
private readonly Subject<T> _proxy = new Subject<T>();
private IDisposable _connection;
public PublishObservable(IObservable<T> source)
{
_source = source;
}
public IDisposable Connect()
{
if(_connection == null)
_connection = _source.Subscribe(_proxy);
var disposable = Disposable.Create(() =>
{
_connection.Dispose();
_connection = null;
});
return _connection;
}
public IDisposable Subscribe(IObserver<T> observer)
{
var _subscription = _proxy.Subscribe(observer);
return _subscription;
}
}
public static class X
{
public static IConnectableObservable<T> Publish<T>(this IObservable<T> source)
{
return new PublishObservable<T>(source);
}
}
Publish creates a single proxy Subject which subscribes to the source observable. The proxy can subscribe/unsubscribe to source based on the connection: Call Connect, and proxy subscribes to source. Call Dispose on the connection disposable and the proxy unsubscribes from source. The important think to take-away from this is that there is a single Subject that proxies any connection to the source. You're not guaranteed only one subscription to source, but you are guaranteed one proxy and one concurrent connection. You can have multiple subscriptions via connecting/disconnecting.
RefCount handles the calling Connect part of things: Here's a simple re-implementation:
// For illustrative purposes only: don't use this code
public class RefCountObservable<T> : IObservable<T>
{
private readonly IConnectableObservable<T> _source;
private IDisposable _connection;
private int _refCount = 0;
public RefCountObservable(IConnectableObservable<T> source)
{
_source = source;
}
public IDisposable Subscribe(IObserver<T> observer)
{
var subscription = _source.Subscribe(observer);
var disposable = Disposable.Create(() =>
{
subscription.Dispose();
DecrementCount();
});
if(++_refCount == 1)
_connection = _source.Connect();
return disposable;
}
private void DecrementCount()
{
if(--_refCount == 0)
_connection.Dispose();
}
}
public static class X
{
public static IObservable<T> RefCount<T>(this IConnectableObservable<T> source)
{
return new RefCountObservable<T>(source);
}
}
A bit more code, but still pretty simple: Call Connect on the ConnectableObservable if refcount goes up to 1, disconnect if it goes down to 0.
Put the two together, and you get a pair that guarantee that there will only be one concurrent subscription to a source observable, proxied through one persistent Subject. The Subject will only be subscribed to the source while there is >0 downstream subscriptions.
Given that introduction, there's a lot of misconceptions in your question, so I'll go over them one by one:
... Publish().RefCount() can be indeed inconsistent. Subscribing a second
time to a published sequence can cause a new subscription to the
source sequence, or not, depending on whether the source sequence was
completed while connected. If it was completed, then it won't be
resubscribed. If it was not completed, then it will be resubscribed.
.Publish().RefCount() will subscribe anew to source under one condition only: When it goes from zero subscribers to 1. If the count of subscribers goes from 0 to 1 to 0 to 1 for any reason then you will end up re-subscribing. The source observable completing will cause RefCount to issue an OnCompleted, and all of its observers unsubscribe. So subsequent subscriptions to RefCount will trigger an attempt to resubscribe to source. Naturally if source is observing the observable contract properly it will issue an OnCompleted immediately and that will be that.
[see sample observable with OnCompleted...] The observable is subscribed twice. The
expected behavior would be that each subscription will receive one
value.
No. The expected behavior is that the proxy Subject after issuing an OnCompleted will re-emit an OnCompleted to any subsequent subscription attempt. Since your source observable completes synchronously at the end of your first subscription, the second subscription will be attempting to subscribe to a Subject that has already issued an OnCompleted. This should result in an OnCompleted, otherwise the Observable contract would be broken.
[see sample observable without OnCompleted as second case...] In the
first case the cold producer (the part before the
Publish().RefCount()) was subscribed only once. The first consumer
received the emitted value, but the second consumer received nothing
(except from an OnCompleted notification). In the second case the
producer was subscribed twice. Each time it generated a value, and
each consumer got one value.
This is correct. Since the proxy Subject never completed, subsequent re-subscriptions to source will result in the cold observable re-running.
My question is: how can we fix this? [..]
The published sequence should propagate to its subscribers all notifications coming directly from the source sequence, and nothing
else.
The published sequence should subscribe to the source sequence when its current number of subscribers increases from zero to one.
The published sequence should stay connected to the source as long as it has at least one subscriber.
The published sequence should unsubscribe from the source when its current number of subscribers become zero.
All of the above currently happens with .Publish and .RefCount currently as long as you don't complete/error. I don't suggest implementing an operator that changes that, breaking the Observable contract.
EDIT:
I would argue the #1 source of confusion with Rx is Hot/Cold observables. Since Publish can 'warm-up' cold observables, it's no surprise that it should lead to confusing edge cases.
First, a word on the observable contract. The Observable contract stated more succinctly is that an OnNext can never follow an OnCompleted/OnError, and there should be only one OnCompleted or OnError notification. This does leave the edge case of attempts to subscribe to terminated observables:
Attempts to subscribe to terminated observables result in receiving the termination message immediately. Does this break the contract? Perhaps, but it's the only contract cheat, to my knowledge, in the library. The alternative is a subscription to dead air. That doesn't help anybody.
How does this tie into hot/cold observables? Unfortunately, confusingly. A subscription to an ice-cold observable triggers a re-construction of the entire observable pipeline. This means that subscribe-to-already-terminated rule only applies to hot observables. Cold observables always start anew.
Consider this code, where o is a cold observable.:
var o = Observable.Interval(TimeSpan.FromMilliseconds(100))
.Take(5);
var s1 = o.Subscribe(i => Console.WriteLine(i.ToString()));
await Task.Delay(TimeSpan.FromMilliseconds(600));
var s2 = o.Subscribe(i => Console.WriteLine(i.ToString()));
For the purposes of the contract, the observable behind s1 and observable behind s2 are entirely different. So even though there's a delay between them, and you'll end up seeing OnNext after OnCompleted, that's not a problem, because they are entirely different observables.
Where it get's sticky is with a warmed-up Publish version. If you were to add .Publish().RefCount() to the end of o in the code above...
Without changing anything else, s2 would terminate immediately printing nothing.
Change the delay to 400 or so, and s2 would print the last two numbers.
Change s1 to only .Take(2), and s2 would start over again printing 0 through 4.
Making this nastiness worse, is the Shroedinger's cat effect: If you set up an observer on o to watch what would happen the whole time, that changes the ref-count, affecting the functionality! Watching it, changes the behavior. Debugging nightmare.
This is the hazard of attempting to 'warm-up' cold observables. It just doesn't work well, especially with Publish/RefCount.
My advice would be:
Don't try to warm up cold observables.
If you need to share a subscription, with either cold or hot observables, stick with #Enigmativity's general rule of strictly using the selector Publish version
If you must, have a dummy subscription on a Publish/RefCount observable. This at least provides a consistent Refcount >= 1, reducing the quantum activity effect.
As Shlomo pointed out, this problem is associated with the Publish operator. The RefCount works fine. So it's the Publish that needs fixing. The Publish is nothing more than calling the Multicast operator with a standard Subject<T> as argument. Here is its source code:
public IConnectableObservable<TSource> Publish<TSource>(IObservable<TSource> source)
{
return source.Multicast(new Subject<TSource>());
}
So the Publish operator inherits the behavior of the Subject class. This class, for very good reasons, maintains the state of its completion. So if you signal its completion by calling subject.OnCompleted(), any future subscribers of the subject will instantly receive an OnCompleted notification. This feature serves well a standalone subject and its subscribers, but becomes a problematic artifact when a Subject is used as an intermediate propagator between a source sequence and the subscribers of that sequence. That's because the source sequence already maintains its own state, and duplicating this state inside the subject introduces the risk of the two states becoming out of sync. Which is exactly what happens when the Publish is combined with the RefCount operator. The subject remembers that the source has completed, while the source, being a cold sequence, has lost its memory about its previous life and is willing to start a new life afresh.
So the solution is to feed the Multicast operator with a stateless subject. Unfortunately I can't find a way to compose it based on the built-in Subject<T> (inheritance is not an option because the class is sealed). Fortunately implementing it from scratch is not very difficult. The implementation below uses an ImmutableArray as storage for the subject's observers, and uses interlocked operations to ensure its thread-safety (much like the built-in Subject<T> implementation).
public class StatelessSubject<T> : ISubject<T>
{
private IImmutableList<IObserver<T>> _observers
= ImmutableArray<IObserver<T>>.Empty;
public void OnNext(T value)
{
foreach (var observer in Volatile.Read(ref _observers))
observer.OnNext(value);
}
public void OnError(Exception error)
{
foreach (var observer in Volatile.Read(ref _observers))
observer.OnError(error);
}
public void OnCompleted()
{
foreach (var observer in Volatile.Read(ref _observers))
observer.OnCompleted();
}
public IDisposable Subscribe(IObserver<T> observer)
{
ImmutableInterlocked.Update(ref _observers, x => x.Add(observer));
return Disposable.Create(() =>
{
ImmutableInterlocked.Update(ref _observers, x => x.Remove(observer));
});
}
}
Now the Publish().RefCount() can be fixed by replacing it with this:
.Multicast(new StatelessSubject<SomeType>()).RefCount()
This change results to the desirable behavior. The published sequence is initially cold, becomes hot when it is subscribed for the first time, and becomes cold again when its last subscriber unsubscribes. And the circle continues with no memories of the past events.
Regarding the other normal case that the source sequence completes, the completion is propagated to all subscribers, causing all of them to unsubscribe automatically, causing the published sequence to become cold. The end result is that both sequences, the source and the published, are always in sync. They are either both hot, or both cold.
Here is a StatelessPublish operator, to make the consumption of the class a little easier.
/// <summary>
/// Returns a connectable observable sequence that shares a single subscription to
/// the underlying sequence, without maintaining its state.
/// </summary>
public static IConnectableObservable<TSource> StatelessPublish<TSource>(
this IObservable<TSource> source)
{
return source.Multicast(new StatelessSubject<TSource>());
}
Usage example:
.StatelessPublish().RefCount()
What's the difference between .Dispose() and .OnCompleted() call on a Subject ?
Usually i dispose subscription to stop listening an observable and complete a subject when it's no longer useful anywhere on the code,
According to the documentation of the Subject<T>.Dispose method:
Releases all resources used by the current instance of the Subject<T> class and unsubscribe all observers.
It seems that attempting to do anything with a Subject after disposing it, results to an ObjectDisposedException. You can't Subscribe to a disposed Subject for example. Any subscriptions that are active at the time the Subject is disposed, will be disposed too, and the unsubscribed observers will not receive OnCompleted notifications.
On the contrary a subject that has been completed by calling its OnCompleted method can still be subscribed at any time, in which case the subscribed observer will receive instantly an OnCompleted notification. Of course if the completed subject is one of the buffered types like the ReplaySubject, then the observers will receive a number of OnNext notifications before the final OnCompleted.
Personally I would consider calling Dispose to a ReplaySubject that is about to be discarded, in order to accelerate the recovery of the RAM used by its internal buffer. I am not sure if this would make any difference though, since the Dispose is generally supposed to release unmanaged resources, and the memory used by the buffer is most probably managed.
Usually i dispose subscription to stop listening an observable and complete a subject when it's no longer usefull[sic] anywhere on the code
I think you have those backwards. I'm not familiar with rx.net, but I do know the IDisposable and Observable patterns. IDisposable is used to release resources from an object when you are completely done with it and it's no longer useful. OnCompleted is for when you are done observing (the provider has finished sending notifications), even if the object might still have other uses.
There is a very important semantic difference between calling .Dispose() and .OnCompleted() on a subject.
Consider this code:
Subject<int> subject = new Subject<int>();
IObservable<int[]> query = subject.ToArray();
IDisposable subscription =
query
.Subscribe(xs => Console.WriteLine(String.Concat(xs)));
subject.OnNext(1);
subject.OnNext(2);
If I then call subject.OnCompleted() I get 12 written to the Console. If, however, I call subject.Dispose() then nothing gets printed.
Some operators, like .ToArray() in my example code, expect the .OnCompleted() call to produce any value.
It is important to understand what queries you are performing on the subject to know how to end it properly - there are situations where both ways are valid.
I feel, though, that you are doing the right things with disposing of subscriptions and completing subjects.
I'm trying to understand when is a good time to return a disposable in the function passed to Observable.Create vs just disposing any resources through scope by a using statement.
Is returning the disposable more for cases where the Observable is an infinite stream? Even if so I don't understand how the using block won't still dispose the resource even if the stream is closed prematurely
I think the Disposable interface on the Observable paradigm is used solely for the purpose of getting rid of the subscription (i.e, stopping the callback on the observed events), as Theodor Zoulias pointed out. It doesn't manage any resources on the stream whatsoever. You might be confusing the use of the Disposable interface on other scenarios.
As regards to disposing subscriptions:
One of the use cases I can see for returning a Disposable is when when you have more than one to call the function on: supposing you had a list of Observables, you could iterate on it and call the function .Dispose() to cancel multiple subscriptions at once.
You could also pass that stream as a disposable to another Observable, to be disposed when some event occurs. Since the entire RX paradigm is about not knowing when things will be executed, this is interesting. I worked at an application where I had to cancel a subscription if a certain event happened, and I passed the Observable Subscription (IDisposable) to the Observer of such event/stream.
Something on these lines:
IDisposable subscription1 = observableOne.Subscribe(_ => # code omitted);
observableTwo.Subscribe(_ => {
subscription1?.Dispose();
subscription1 = null;
});
As Enigmaticy has pointed out, although this exemplifies my point, a better way to accomplish this would be:
observableOne.TakeUntil(observableTwo).Subscribe(_ => #code ommited);
I haven't worked with C# in a while but these are the use cases I can see on using vs Disposable as object. It gives you greater flexibility on when you want to cancel your subscriptons :~
Thanks to everyone responding in this post it's helped me understand a bit better. I've had a lot of stumbling in my understanding of RX and I think a lot of this just comes down to limited documentation and seems like many people online don't quite understand perfectly either so there's a lot of misinformation to sort through.
This other answer does the trick for me
https://stackoverflow.com/a/7707768/7183974 .
What it really comes down to is for when we have non-blocking code in our Observable.Create method. So when our observable is subscribed to we instantly return a disposable that can clean up any asynchronous / concurrent processes in the event that we need to cancel a subscription early.
This is necessary for cases where maybe your observable is using other async (push-based) code.
For iterative (pull-based) code that you simply want to be push based then you can use Observable.Create but TBH I think just using an Iterator is better and if you need it to be a push-based API then just use ToObservable.
I was trying to implement a push-based iterator so the disposable seemed redundant to me which is what confused me. I've since refactored my code to be pull-based and if I ever were to need it to be push-based again I would just use ToObservable.
I have a lot of code in my project like Hit and mute by using Reactive extension like this way:
IDisposable dsp = null;
dsp = TargetObservable.Subscribe((incomingContent) =>
{
if (incomingContent == "something")
{
myList.Add(incomingContent);
dsp.Dispose();
}
});
First of all, I concerns about the thread safety since my Observable is quite busy and have bunch of content pushing all the way, but later, I was told I should combine with the ObserveOn(thread) to guarantee thread safe, I totally agree, so let's forget the thread safe thing.
Here I want to know:
How or when I should call the Dispose for an observable.
What's the correct way to satisfy Hit and mute, combine with some complete-able extension method like Take(count), 'TakeWhile(predict)'?
If OnComplete() called, the Dispose() will be called internally, correct? Then the reference relationship between the Observer and Observable will break(because my observable is a long life static instance, the reference would cause memory leak).
I would avoid following the pattern you have here. It makes it difficult to understand the problem space if other devs have to mix global state with the inner function for the subscribe/OnNext handler.
You are much better off creating the TakeWhile/TakeUntilIncluding extension method which encapsulates the sequence termination. Then you can separate your 'adding to the list' concern.
An alternatitve thing to do is the super-simple:
var subscription = source.Where(x => x=="something")
.Take(1)
.Subscribe(incomingContent=>myList.Add(incomingContent));