'Why can I use .Select on an observable that is not a list?

The Select extension from System.Reactive.Linq is documented as :

Projects each element of an observable sequence into a new form with the specified source and selector.

This behavior sounds only applicable to Lists or IEnumerable-like objects. However I can do this with no issue :

IObservable<int> observable = Observable.Return(42);
observable.Select(e => "");

Why does this code compiles and executes successfully ? Why is it allowed ?



Solution 1:[1]

From your link to doc about method:
Observable.Select<TSource, TResult> Method (IObservable<TSource>, Func<TSource, TResult>)

Observable.Select is an extension method for IObservable<TSource>.

Solution 2:[2]

Probably you are used to the Select method that is defined as an extension method defined on IEnumerable<T>. That method runs a method for each item in the sequence to transform the input IEnumerable<T> into an output IEnumerable<U> which can be of different type.

The Select method defined on IObservable<T> is the reactive counterpart of that method and transforms each value emitted by an Observable<T> and hence creates an Observable<U>.

In general, there is kind of a symmetry between the Linq extension methods defined on IEnumerable<T> and the reactive extension methods defined on IObservable<T>. You can think of an IObservable<T> as a sequence of items that come in one by one over time.

In your example, you define an observable emitting only one value 42 analog to an IEnumerable<int> that contains only one value. The Select statement transforms this observable into an IObservable<string> which emits one empty string.

The question is now when this value will be emitted: Reactive extensions has a deferred execution logic which is also similar to the deferred execution known from common Linq. This means that the value of the observable will be emitted the moment you subscribe to that observable.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Lukasz Szczygielek
Solution 2 Döharrrck