Overview

18 Data streams and the Reactive Extensions

In this chapter, data streams are introduced as values delivered over time, and the Reactive Extensions are presented as the functional toolkit for working with them. The core abstraction is IObservable<T>, which fits alongside familiar .NET types by representing asynchronous sequences, while IEnumerable<T> remains a pull-based sequence and Task<T> a single asynchronous result. The chapter emphasizes the push-based nature of observables: consumers subscribe, producers push values, and the observable contract allows a stream to emit many values, then either complete successfully or fail with an error.

Once the basic contract is clear, the chapter shows how to create observables from a variety of sources, including timers, user input, callback-based APIs, single values, tasks, and existing enumerables. Subscription is handled through Subscribe, which can take callbacks or an IObserver, and returns an IDisposable so the consumer can unsubscribe. The discussion also highlights the importance of laziness and why some imperative mechanisms, such as Subject, are useful for illustration but generally less desirable than more declarative creation patterns like Observable.Create.

The later part of the chapter focuses on composing streams with operators such as Select, SelectMany, Concat, Merge, Partition, CombineLatest, Sample, and Scan. Through examples like exchange-rate lookup, key-sequence detection, and monitoring bank-account balances, it shows how Rx can express transformations, coordination between streams, error separation, and stateful logic without explicit mutable state. The chapter closes by explaining when observables are a good fit: especially for one-way, event-driven dataflows where patterns span multiple events, but less so for independent events, request-response interactions, or situations that demand lower-level synchronization control.

Marble diagrams provide an intuitive way to understand IObservables.
Select maps a function onto a stream.
Concat waits for an IObservable to complete and then produces elements from the other IObservable.
Merge merges two IObservables into one.
Partitioning an IObservable according to a predicate
Simple dataflow between three IObservables
Dataflow with a separate branch for handling errors
CombineLatest signals whenever one of two IObservables signals.
Sample produces the values from a source stream when a sampler stream signals.
Scan aggregates all values produced so far.

Summary

  • IObservable<T> represents a stream of Ts, a sequence of values in time.
  • An IObservable produces messages according to the grammar
  • Writing a program with IObservables involves three steps:
    • Create IObservables using the methods in System.Reactive.Linq .Observable.
    • Transform and combine IObservables using the operators in Rx or other operators you may define.
    • Subscribe to and consume the values produced by the IObservable.
  • Associate an observer to an IObservable with Subscribe.
  • Remove an observer by disposing of the subscription returned by Subscribe.
  • Separate side effects (in observers) from logic (in stream transformations).
  • When deciding on whether to use IObservable, consider the following:
    • IObservable allows you to specify logic that spans multiple events.
    • IObservable is good for modeling unidirectional dataflows.

FAQ

```html
What is an IObservable in Rx?

An IObservable represents a stream of values over time. Unlike IEnumerable, which you enumerate at your leisure, an IObservable pushes values to subscribers as they become available.

How is IObservable different from IAsyncEnumerable?

IAsyncEnumerable is consumer-centric and pulls data when the consumer requests it. IObservable is producer-centric and pushes data to observers when values are available.

What messages can an IObservable produce?

An IObservable can produce OnNext messages for values, OnCompleted for normal completion, and OnError for abnormal termination with an exception.

How do you subscribe to an IObservable?

You subscribe by calling Subscribe, either with callback handlers such as onNext, onError, and onCompleted, or by passing an IObserver.

Why does Subscribe return an IDisposable?

The returned IDisposable represents the subscription. Disposing it unsubscribes from the observable and stops receiving further messages.

How can you create a timer as an IObservable?

You can use Observable.Interval to create an observable that signals at regular intervals, such as once per second, producing a growing counter value over time.

Why is Subject discouraged in Rx?

Subject is useful for demonstrations, but it is imperative: you manually tell it when to emit values. This goes against the more declarative, reactive style recommended in Rx, so it should be avoided when possible.

How do you transform an IObservable?

You can use operators like Select to map each item in the stream, and SelectMany to flatten nested observables, much like Bind in other functional contexts.

How do you combine or partition observables?

Use operators such as Concat, Merge, and StartWith to combine streams, and Partition to split a stream into two streams based on a predicate.

When should you use IObservable?

Use IObservable when your logic spans multiple events, when you want to model one-way dataflows, or when you need to react to ongoing streams of data. If events are independent or you need request-response behavior, IObservable is often not the best fit.

```

pro $24.99 per month

  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose one free eBook per month to keep
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime

lite $19.99 per month

  • access to all Manning books, including MEAPs!

team

5, 10 or 20 seats+ for your team - learn more


Close
choose your plan

team

monthly
annual
$49.99
$499.99
only $41.67 per month
  • five seats for your team
  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose another free product every time you renew
  • choose twelve free products per year
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime
  • renews annually, pause or cancel renewal anytime
  • Functional Programming in C#, Second Edition Functional Programming in C#, Second Edition ebook for free
Close
choose your plan

team

monthly
annual
$49.99
$499.99
only $41.67 per month
  • five seats for your team
  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose another free product every time you renew
  • choose twelve free products per year
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime
  • renews annually, pause or cancel renewal anytime
  • Functional Programming in C#, Second Edition Functional Programming in C#, Second Edition ebook for free
Close
choose your plan

team

monthly
annual
$49.99
$499.99
only $41.67 per month
  • five seats for your team
  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose another free product every time you renew
  • choose twelve free products per year
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime
  • renews annually, pause or cancel renewal anytime
  • Functional Programming in C#, Second Edition Functional Programming in C#, Second Edition ebook for free