---
title: "Reactive Extensions (Rx) - Part 5 - Awaiting Observables - Muhammad Rehan Saeed"
description: "How and where to use Task Parallel Library (TPL) async and await with Reactive Extensions (Rx). Also, how to use TPL for awaiting observables."
canonical_url: "https://rehansaeed.com/reactive-extensions-part5-awaiting-observables/"
last_updated: "2014-03-27T00:00:00+00:00"
meta:
  author: "Muhammad Rehan Saeed"
  keywords: ".NET,async await,Rx,Task Parallel Library,TaskCompletionSource,TPL"
  "og:description": "How and where to use Task Parallel Library (TPL) async and await with Reactive Extensions (Rx). Also, how to use TPL for awaiting observables."
  "og:image": "https://rehansaeed.com/_og/s/o_93705cab83e7de0d.png"
  "og:image:alt": "Reactive Extensions (Rx) - Part 5 - Awaiting Observables - Muhammad Rehan Saeed"
  "og:image:height": "630"
  "og:image:type": image/png
  "og:image:width": "1200"
  "og:title": "Reactive Extensions (Rx) - Part 5 - Awaiting Observables"
  "twitter:image": "https://rehansaeed.com/_og/s/o_93705cab83e7de0d.png"
  "twitter:image:alt": "Reactive Extensions (Rx) - Part 5 - Awaiting Observables - Muhammad Rehan Saeed"
---

> Index of every page on this site: [llms.txt](https://rehansaeed.com/llms.txt)

# [Reactive Extensions (Rx) - Part 5 - Awaiting Observables](https://rehansaeed.com/reactive-extensions-part5-awaiting-observables/)

Posted 27 March 2014 - **4 min read**

![Reactive Extensions](https://rehansaeed.com/_ipx/f_webp&s_2560x1440/images/hero/Reactive-Extensions-1366x768.png)

1. [Reactive Extensions (Rx) - Replacing C# Events](https://rehansaeed.com/reactive-extensions-part1-replacing-events/)
2. [Reactive Extensions (Rx) - Wrapping C# Events](https://rehansaeed.com/reactive-extensions-part2-wrapping-events/)
3. [Reactive Extensions (Rx) - Naming Conventions](https://rehansaeed.com/reactive-extensions-part3-naming-conventions/)
4. [Reactive Extensions (Rx) - Replacing Timers](https://rehansaeed.com/reactive-extensions-part4-replacing-timers/)
5. [Reactive Extensions (Rx) - Awaiting Observables](https://rehansaeed.com/reactive-extensions-part5-awaiting-observables/)
6. [Reactive Extensions (Rx) - Task ToObservable](https://rehansaeed.com/reactive-extensions-part6-task-toobservable/)
7. [Reactive Extensions (Rx) - Sample Events](https://rehansaeed.com/reactive-extensions-part7-sample-events/)
8. [Reactive Extensions (Rx) - Timeouts](https://rehansaeed.com/reactive-extensions-rx-part-8-timeouts/)

So I've just finished extolling the wonderful virtues of `TaskCompletionSource` with a colleague and thought I'd share the joy more widely. Eventually this will turn into a post about how great Reactive Extensions (Rx) is, I promise.

# TaskCompletionSource

[TaskCompletionSource](http://msdn.microsoft.com/en-us/library/dd449174%28v=vs.110%29.aspx) is a great tool to turn any asynchronous operation which does not follow the Task Parallel Library (TPL) pattern into a Task. The example below is something I've started to do in a few places.

```cs
public Task<bool?> ShowDialog()
{
    TaskCompletionSource<bool?> taskCompletionSource = new TaskCompletionSource<bool?>();

    Window window = new MyDialogWindow();
    EventHandler eventHandler = null;
    eventHandler = 
        (sender, e) =>
        {
            window.Closed -= eventHandler;
            taskCompletionSource.SetResult(window.DialogResult);
        };
    window.Closed += eventHandler;
    window.Show();

    return taskCompletionSource.Task;
}
```

In the example above we are creating a new window, registering for its `Closed` event and then showing the window. When the window is closed, we de-register from the closed event handler (To avoid a remaining reference to the window, causing a memory leak) and the `DialogResult` of the window is passed to the `TaskCompletionSource` using the `SetResult` method.

The `TaskCompletionSource` gives us a nice `Task` object which we can return at the end of the method. When we return the task its status is `WaitingForActivation`. Only when the `SetResult` method is called when the window closes, does the tasks status change to `RanToCompletion`.

This whole operation has been wrapped up and packaged nicely in a `Task<bool?>` with a nice bow on top with the help of `TaskCompletionSource`. Now we can call the method and await the results from the method call, thus allowing us to savour the power and simplicity the TPL affords us.

```cs
bool? result = await ShowDialog();
```

There are other great ways to use `TaskCompletionSource` of course. Generally speaking though I have found myself using it to turn an operation where I am waiting for an event into a task. For [more information](http://blogs.msdn.com/b/pfxteam/archive/2009/06/02/9685804.aspx) on `TaskCompletionSource` or the TPL in general I highly recommend reading [Stephen Toub's blog](http://blogs.msdn.com/b/pfxteam/).

# Awaiting Observables

Having showed my colleague the above example and feeling very content, I suddenly realised that Reactive Extensions (Rx) can make the code even simpler. With the advent of the latest version of Reactive Extensions (Rx) you can now await observables and we can turn the method above into this:

```cs
public async Task<bool?> ShowDialog()
{
    var window = new MyDialogWindow();
    var closed = Observable
        .FromEventPattern<EventHandler, EventArgs>(
            h => window.Closed += h,
            h => window.Closed -= h);

    window.Show();
    await closed.FirstAsync()

    return window.DialogResult;
}
```

The `await` keyword is just some syntactic sugar in the C# language that makes writing thorny asynchronous code effortless. The real meat of what drives it is the `GetAwaiter` method. The Reactive Extensions (Rx) team seeing the genius that is the Task Parallel Library (TPL) took advantage. They added this method (actually an extension method) to `IObservable<T>`, allowing us to await an observable as seen in the example above.

However, there is a caveat which I shall explain. In the example above the Closed event could conceivably be fired any number of times (If the window was opened and closed a few times) and the observable wrapper around the Closed event never completes. So our observable returns multiple results but a task can only return a single result.

The secret in our example is the `FirstAsync` method. We are actually awaiting the first result returned by our observable and don't care about any further results. By default awaiting an observable without the `FirstAsync` method above will actually await the last result **before completion**. If your observable does not complete, then you will be waiting **forever**!

Handily the Reactive Extensions (Rx) team has added several methods which you can use before you use `await` to modify the result of what you are awaiting. All of these methods end with the word `Async`. I've added a short list of these methods below (There are lots of overloads so I've just highlighted the main ones):

```cs
// Returns the first element of an observable sequence.
string result = await observable.FirstAsync();

// Returns the first element of an observable sequence, or a default value if no such element exists.
string result = await observable.FirstOrDefaultAsync();

// Returns the last element of an observable sequence. 
// This is the default action of awaiting an observable.
string result = await observable.LastAsync();

// Returns the last element of an observable sequence, 
// or a default value if no such element exists.
string result = await observable.LastOrDefaultAsync();

// Returns the only element of an observable sequence, and throws an exception if there is not exactly 
// one element in the observable sequence.
string result = await observable.SingleAsync();

// Returns the only element of an observable sequence, or a default value if the observable sequence 
// is empty; this method reports an exception if there is more than one element in the observable sequence.
string result = await observable.SingleOrDefaultAsync();

// Invokes an action for each element in the observable sequence and returns a Task that will get 
// signalled when the sequence terminates.
await observable.ForEachAsync(x => Console.WriteLine(x));
```

All of the above methods allow you to pick a single result from your observable. `ForEachAsync` is different though as it performs an action on each item and when your observable completes (If it does) then the task completes.

# Conclusions

So we've learned how to await observables in different ways and how it can be another way of doing the same thing that `TaskCompletionSource` does but in a cleaner more elegant way.

We've also learned that there are some caveats that you need to be aware of when awaiting an observable i.e. that observables return multiple results and you have to pick one to return in your task.

## Web Mentions

[What's this?](https://en.wikipedia.org/wiki/Webmention)

### 0 Linked

### 0 Replies

## Comment

[Leave and View Directly on GitHub.com](https://github.com/RehanSaeed/rehansaeed.github.io/issues/107)

2 Comments

[![RehanSaeed](https://avatars.githubusercontent.com/u/2270364?v=4)](https://github.com/RehanSaeed)

[RehanSaeed](https://github.com/RehanSaeed) [12 May 2020](https://github.com/RehanSaeed/rehansaeed.github.io/issues/107#issuecomment-627272789)

[![David Christensen](https://camo.githubusercontent.com/e32cce8adda5f86d4ece2d8a0322260ab87e14a6f8f737f157b53d4034d5f662/68747470733a2f2f7777772e67726176617461722e636f6d2f6176617461722f31333131396535633030383166393464353464346663633562323530313761663f733d393626643d6d6d26723d67)](https://camo.githubusercontent.com/e32cce8adda5f86d4ece2d8a0322260ab87e14a6f8f737f157b53d4034d5f662/68747470733a2f2f7777772e67726176617461722e636f6d2f6176617461722f31333131396535633030383166393464353464346663633562323530313761663f733d393626643d6d6d26723d67) **David Christensen** commented on **2017-01-11 12:04:21**

In your observable ShowWindow example, I believe there is a (potential) race condition. Shouldn't your code be as shown below? Obviously for this particular example there is unlikely to be a problem, if you are demonstrating a pattern it might be worth correcting it?

```
public async Task ShowDialog()
{
    Window window = new MyDialogWindow();
    var closing= Observable
        .FromEventPattern(
            h => window.Closed += h,
            h => window.Closed -= h);

    window.Show();
    await closing
        .FirstAsync();
 
    return window.DialogResult;
}
```

[![RehanSaeed](https://avatars.githubusercontent.com/u/2270364?v=4)](https://github.com/RehanSaeed)

[RehanSaeed](https://github.com/RehanSaeed) [12 May 2020](https://github.com/RehanSaeed/rehansaeed.github.io/issues/107#issuecomment-627272831)

[![Muhammad Rehan Saeed](https://camo.githubusercontent.com/8a07049df41b8a3839a3f4342f09ea8e6e7fa0065667687f04beca2d088a1dca/68747470733a2f2f7777772e67726176617461722e636f6d2f6176617461722f32623266393030653361633066353535316462646537323864336262343935343f733d393626643d6d6d26723d67)](https://camo.githubusercontent.com/8a07049df41b8a3839a3f4342f09ea8e6e7fa0065667687f04beca2d088a1dca/68747470733a2f2f7777772e67726176617461722e636f6d2f6176617461722f32623266393030653361633066353535316462646537323864336262343935343f733d393626643d6d6d26723d67) **[Muhammad Rehan Saeed](https://rehansaeed.com/)** commented on **2017-01-11 14:25:38**

> In your observable ShowWindow example, I believe there is a (potential) race condition. Shouldn't your code be as shown below? Obviously for this particular example there is unlikely to be a problem, if you are demonstrating a pattern it might be worth correcting it?
>
> ```
> public async Task ShowDialog()
> {
>     Window window = new MyDialogWindow();
>     var closing= Observable
>         .FromEventPattern(
>             h => window.Closed += h,
>             h => window.Closed -= h);
>
>     window.Show();
>     await closing
>         .FirstAsync();
>  
>     return window.DialogResult;
> }
> ```

Corrected, thanks!

```json
{"@context":"https://schema.org","@graph":[{"@id":"https://rehansaeed.com/#website","@type":"WebSite","description":"Software Developer at Microsoft, YouTuber, Open Source Contributor and Blogger","inLanguage":"en-GB","name":"Muhammad Rehan Saeed","url":"https://rehansaeed.com/","author":{"@id":"https://rehansaeed.com/#identity"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https://rehansaeed.com/?search={search_term_string}"},"query-input":"required name=search_term_string"}],"publisher":{"@id":"https://rehansaeed.com/#publisher"}},{"@id":"https://rehansaeed.com/reactive-extensions-part5-awaiting-observables/#webpage","@type":"WebPage","dateModified":"2014-03-27T00:00:00+00:00","datePublished":"2014-03-27T00:00:00+00:00","description":"How and where to use Task Parallel Library (TPL) async and await with Reactive Extensions (Rx). Also, how to use TPL for awaiting observables.","name":"Reactive Extensions (Rx) - Part 5 - Awaiting Observables","url":"https://rehansaeed.com/reactive-extensions-part5-awaiting-observables/","breadcrumb":{"@id":"https://rehansaeed.com/reactive-extensions-part5-awaiting-observables/#breadcrumb"},"isPartOf":{"@id":"https://rehansaeed.com/#website"},"potentialAction":[{"@type":"ReadAction","target":["https://rehansaeed.com/reactive-extensions-part5-awaiting-observables/"]}]},{"@id":"https://rehansaeed.com/#identity","@type":"Person","name":"Muhammad Rehan Saeed","url":"https://rehansaeed.com/about/","image":{"@id":"https://rehansaeed.com/#/schema/image/1"},"sameAs":["https://github.com/RehanSaeed","https://www.linkedin.com/in/muhammad-rehan-saeed","https://stackoverflow.com/users/1212017/muhammad-rehan-saeed","https://www.youtube.com/c/MuhammadRehanSaeed","https://www.twitch.tv/rehansaeeduk"]},{"@id":"https://rehansaeed.com/#publisher","@type":"Organization","logo":"https://rehansaeed.com/images/schema/Publisher-600x60.png","name":"Muhammad Rehan Saeed","url":"https://rehansaeed.com"},{"@id":"https://rehansaeed.com/reactive-extensions-part5-awaiting-observables/#article","@type":"Article","dateModified":"2014-03-27T00:00:00+00:00","datePublished":"2014-03-27T00:00:00+00:00","description":"How and where to use Task Parallel Library (TPL) async and await with Reactive Extensions (Rx). Also, how to use TPL for awaiting observables.","headline":"Reactive Extensions (Rx) - Part 5 - Awaiting Observables","inLanguage":"en-GB","url":"https://rehansaeed.com/reactive-extensions-part5-awaiting-observables/","author":{"@id":"https://rehansaeed.com/#identity"},"image":[{"@type":"ImageObject","url":"https://rehansaeed.com/images/hero/Reactive-Extensions-1366x768.png","caption":"Reactive Extensions","width":"1366","height":"768"}],"isPartOf":{"@id":"https://rehansaeed.com/reactive-extensions-part5-awaiting-observables/#webpage"},"keywords":[".NET","async await","Rx","Task Parallel Library","TaskCompletionSource","TPL"],"mainEntityOfPage":{"@id":"https://rehansaeed.com/reactive-extensions-part5-awaiting-observables/#webpage"},"publisher":{"@id":"https://rehansaeed.com/#publisher"}},{"@id":"https://rehansaeed.com/reactive-extensions-part5-awaiting-observables/#breadcrumb","@type":"BreadcrumbList","itemListElement":[{"@type":"ListItem","name":"Blog","item":"https://rehansaeed.com/","position":1},{"@type":"ListItem","name":"Reactive Extensions (Rx) - Part 5 - Awaiting Observables","item":"https://rehansaeed.com/reactive-extensions-part5-awaiting-observables/","position":2}]},{"@id":"https://rehansaeed.com/#/schema/image/1","@type":"ImageObject","contentUrl":"https://rehansaeed.com/images/author/Muhammad-Rehan-Saeed/Logo-512x512.png","inLanguage":"en-GB","url":"https://rehansaeed.com/images/author/Muhammad-Rehan-Saeed/Logo-512x512.png"}]}
```

## Sitemap

See the full [sitemap](https://rehansaeed.com/sitemap.md) for all pages.
