Rok
Rok

Reputation: 705

Observer subscribed to multiple observables is not completed

I am trying to learn about RX and am subscribing a created observer to two different observables.

var observer = Observer.Create<string>(x => Console.WriteLine(x), 
            () => Console.WriteLine("Completed"));

var subscription1 = Observable.Interval(TimeSpan.FromSeconds(1))
            .Select(x => "X" + x)
            .Subscribe(observer);

var subscription2 = Observable.Interval(TimeSpan.FromSeconds(2))
           .Select(x => "YY" + x)
           .Subscribe(observer);

Console.WriteLine("Unsubscribing in 5 seconds");
Thread.Sleep(5000);
subscription1.Dispose();
subscription2.Dispose();

Console.WriteLine("All disposed");

I would expect that after disposal of subscription1 the observer would be completed. What am I missing here? Currently I get the following console output from the code above:

Unsubscribing in 5 seconds
X0
YY0
X1
X2
YY1
X3
All disposed

Upvotes: 1

Views: 187

Answers (1)

Fratyx
Fratyx

Reputation: 5797

Observable.Interval creates an infinite sequence so you never will get the 'completed' message. By unsubscribing you just stop listening to this infinite sequence.

If you want the sequence to be completed you could use something like Observable.Interval(...).Take(3).

Upvotes: 3

Related Questions