Skip to content

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

@fedeAlterio

Description

@fedeAlterio

Consider this code

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!

var inner = await xs.SubscribeSafeAsync(innerObserver).ConfigureAwait(false);
await disposable.AssignAsync(inner).ConfigureAwait(false);

If you want I can provide a PR with the fix

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions