Rx Subscriptions and Garbage Collection

Do you need to assign the IDisposable returned by the variable to a IObservable.Subscribevariable to protect the subscription from garbage collection or is an active subscription sufficient?

My use case: I create a one-time observable from an existing observable ( myObservablein the example):

myObservable.Take(1).Subscribe(fun v -> printfn "One-shot: %A" v) |> ignore
+4
source share
2 answers

, . , GC , , , , . , , , .

, , .Take(1) , .

+5

Rx.NET 2.2 , , .

, , (OnComplete/OnError). - http://introtorx.com/Content/v1.0.10621.0/03_LifetimeManagement.html#Finalizers

, , . , , , .

( #, )

var myObservable = Observable.Timer(TimeSpan.FromSeconds(1));
myObservable.Take(1).Subscribe(v => Console.WriteLine($"One-shot: {v}"));

//Force full GC.
GC.Collect();
//Wait for any Finalizers
GC.WaitForPendingFinalizers();
//Then clear out anything kept by finalizers.
GC.Collect();

//We will still see "One-shot: 0" written to the console.
+2

All Articles