×
Namespaces

Variants
Actions
Revision as of 02:45, 26 July 2013 by hamishwillee (Talk | contribs)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

Observable vs. Task

From Nokia Developer Wiki
Jump to: navigation, search

This article explains when to use observables and when to use tasks.

SignpostIcon XAML 40.png
WP Metro Icon WP8.png
SignpostIcon WP7 70px.png
Article Metadata
CompatibilityArticle
Created: paulo.morgado (08 Jul 2013)
Last edited: hamishwillee (26 Jul 2013)

Contents

Introduction

In Implementing GeoCordinateWatcher as a Reactive Service we saw how to convert an event-based asynchronous API into an API based on observables, while in Bringing async/await to the Contacts service we saw how to convert to an API based on tasks.

This article answers the question "in what circumstances should each of the techniques be used".


When to use observables

Reactive Programming allows you to compose asynchronous and event-based programs using observable sequences and LINQ-style query operators. It is very suited to handling, combining and filtering streams of events.

The need to combine several event streams or filtering is a good clue for the use of observables.

When to use tasks

As the name suggests, a task is something that has a beginning and an end. So, all asynchronous APIs based on callbacks or events are candidates to be converted into a task-based asynchronous API.


Applicability matrix

Another way to look at this is:

  • Tasks are for a single future value
  • Observables are for multiple future values

The following table shows the correspondence between asynchronous APIs and their synchronous counterparts:

Synchronous Asynchronous
Single Value -
// synchronous call
var x = F(42);
 
// synchronous call
var y = G(x);
Task
// asynchronous call
var x = FAsync(42);
 
// asynchronous call
var y = GAsync(x);
Multiple Values Enumerable
// Shopping database
var res =
from o in orders
from p in p.Products
where p.Price > 29.95m
select p.Name;
 
// Synchronous MoveNext
foreach (var p in res)
{
Console.WriteLine(p);
}
Observable
// Stock trade events
var res =
from t in trades
from q in t.Symboils
where q.Quote > 29.95m
select q.Symbol;
 
// Asynchronous MoveNext
res.Subscribe(p => Console.WriteLine(p));

References

This page was last modified on 26 July 2013, at 02:45.
119 page views in the last 30 days.