-1

I am wondering why my Observable does not produce any element when i am not awaiting its source which is an IAsyncEnumerable.I am using a Select over the Observable, and nothing comes out of it , my code does not execute.


public async IAsyncEnumerable<int> GetAsyncEnumerable()
{
    int i=0;
    while(true)
    {
       await Task.Delay(1000);
       yield return i++;
    }
}
public async Task Run()
{
    IAsyncEnumerable<int> enumerable=GetAsyncEnumerable().ToObservable();

    await foreach(var elem in enumerable)
    {
            Console.WriteLine(elem);
    }
}

In the above example , the code works and is called while below there is nothing coming out.

public async Task RunObs()
{
    IAsyncEnumerable<int> enumerable=GetAsyncEnumerable().ToObservable();
    IObservable<int> inputObs = enumerable.ToObservable();
    var outputObs = inputObs
                    .Select(elem=>
                    { 
                        Console.WriteLine(elem); //does not execute
                        return elem;
                    });
}

Do I need to store somewhere the reference to this observable, or how should one do this?

Bercovici Adrian
  • 8,794
  • 17
  • 73
  • 152

1 Answers1

1

The observable does not produce any elements, because you need to subscribe to it to it to get them.

When you await an observable you implicitly subscribe to the observable, the method will return when the observable completes or errors. If it completes you will receive the last value produced.

    var outputObs = await GetAsyncEnumerable()
                    .ToObservable()
                    .Select(elem =>
                    {
                        Console.WriteLine(elem); 
                        return elem;
                    })
                    .Take(5);
    Console.WriteLine(outputObs);

will output 0, 1, 2, 3, 4, 4 on the console(each number on different lines of course)

This will also cause the observable to produce output:

    GetAsyncEnumerable()
                    .ToObservable()
                    .Take(5)
                    .Subscribe(elem =>
                    {
                        Console.WriteLine(elem);                        
                    });

0, 1, 2, 3, 4

Because now you also subsribed to the observable. Hope it makes sense?

Magnus
  • 353
  • 3
  • 8