Skip to content

Observable.Start documentation #2162

@RedGlow

Description

@RedGlow

In "intro to RX", Part I, "Creating Observable Sequences", I read that:

Note the difference between Observable.Start and Observable.Return. The Start method invokes our callback only upon subscription, so it is an example of a 'lazy' operation. Conversely, Return requires us to supply the value up front. [...] Start doesn't begin the work until you subscribe to it. Moreover, it will re-execute the callback every time you subscribe to it. So it is more like a factory for a task-like entity.

But the documentation of Observable.Start, in its "remarks" section, states the contrary:

The action is called immediately, not during the subscription of the resulting sequence.
Multiple subscriptions to the resulting sequence can observe the action's outcome.

I performed a little test (using the code in the book as template):

using System.Reactive.Linq;

void StartAction()
{
    var start = Observable.Start(() =>
    {
        Console.WriteLine($"{DateTime.Now} - Start working.");
        for (var i = 0; i < 10; i++)
        {
            Thread.Sleep(100);
            Console.Write(".");
        }
        Console.WriteLine($"\n{DateTime.Now} - Work completed.");
    });

    Console.WriteLine($"{DateTime.Now} - Waiting a little before subscribing...");
    Thread.Sleep(2000);
    Console.WriteLine($"{DateTime.Now} - Ok, subscribing!");
    start.Subscribe(
        _ => Console.WriteLine("SUB1: Unit published"), 
        () => Console.WriteLine("SUB1: Action completed"));
    
    start.Subscribe(
        _ => Console.WriteLine("SUB2: Unit published"), 
        () => Console.WriteLine("SUB2: Action completed"));
}

StartAction();
Thread.Sleep(2100);

And indeed the inline documentation seems right and the book wrong. In the output we can see that a) the computation starts before any subscription, and b) it does not re-execute the callback for every subscription.

13-Aug-24 9:37:15 AM - Start working.
13-Aug-24 9:37:15 AM - Waiting a little before subscribing...
..........
13-Aug-24 9:37:16 AM - Work completed.
13-Aug-24 9:37:17 AM - Ok, subscribing!
SUB1: Unit published
SUB1: Action completed
SUB2: Unit published
SUB2: Action completed

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions