dotnet / dotnet/reactive

AsyncRx.Net Switch subscribes to newer and then unsubscribes from older and not vice versa

Open
#2,257 0 comments 0 reactions 0 assignees View on GitHub
Dominant language
C#
Stars
7.2k
Forks
798
PR merge metrics
No merged PRs in 30d

Description

Consider this code

```csharp
var timer1 = AsyncObservable.Interval(TimeSpan.FromSeconds(1))
.Do(x => Console.WriteLine($"Timer 1 tick {x}"), e => { }, () => { })
.Finally(() => Console.WriteLine("Unsubscribed from timer 1"));

var timer2 = AsyncObservable.DeferAsync(async () =>
{
Console.WriteLine("Subscribing timer 2");
await Task.Delay(100);
return AsyncObservable.Interval(TimeSpan.FromMilliseconds(100))
.Finally(async () =>
{
Console.WriteLine("Unsubscribing timer 2");
await Task.Delay(1000);
Console.WriteLine("Unsubscribed timer 2");
});
});

await timer1.Select(_ => timer2)
.Take(3)
.Switch()
.SubscribeAsync(_ => {});

Console.Read();
```

The output is

> Timer 1 tick 0
Subscribing timer 2
Timer 1 tick 1
Subscribing timer 2
Unsubscribing timer 2
Unsubscribed timer 2
Timer 1 tick 2
Subscribing timer 2
Unsubscribing timer 2
Unsubscribed timer 2
Unsubscribed from timer 1

This is incorrect, since it first subscribes to the newer observable, and then it unsubscribes from the previous.
The issue that it first subscribes to the inner observable, and the assign it to the serialDisposable, that disposes the older, but its too late since we are already subscribed!

https://github.com/dotnet/reactive/blob/1ce85f4066360193cea9da5b94def4c32552c3be/AsyncRx.NET/System.Reactive.Async/Linq/Operators/Switch.cs#L96-L98

If you want I can provide a PR with the fix

Contributor guide

No contributing guide indexed for this repository

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.