Reactive Extensions (RX)
Tamir Dresher
Senior Software Architect
June 19, 2013
Slides: Bart De Smet
About Me
•
•
•
•
•

Software architect, consultant and instructor
Technology addict
10 years of experience
.NET and Native...
Applications And Data
GPS

RSS

feeds

Social
media

Server management
Recovery
Projection
Aggregating

from quote in stock
where quote.Symbol == “MSFT”
select quote.Value

IObservable<T>

ISch...
The building blocks
• Observables
– Producers (.NET events, WinRT Events, Sensors, APM method etc.)

• Observers
– Consume...
Essential Interfaces
namespace System
{
public interface IObservable<out T>
{
IDisposable Subscribe(IObserver<T> observer)...
Notification Grammar
OnNext(42)

OnNext(43)

OnNext(“Hello”)

OnNext

OnCompleted

OnError(error)

OnError OnCompleted
Limitations of .NET Events
exchange.StockTick += (sender, args) =>
{
if (args.Quote.Symbol == “MSFT”)
{
// Imperative code...
Observable Sequences to the Rescue
IObservable<Quote> stockQuotes = …;
var msft = stockQuotes

.Where(quote => quote.Symbo...
Dictionary Suggest
Asynchronous
request
React

Dictionary web
service

Reaction
Reactive
Reactor

Data binding
on UI threa...
Demo
Converting Events and Asynchronous Methods
// Convert the TextChanged event to IObservable<string>
var input = (from evt i...
Stock Trade Analysis
MSFT
27.01

INTC
21.75

from tick in ticks

MSFT
27.96

MSFT
31.21

INTC
22.54

INTC
20.98

MSFT
30.7...
Stock Trade Analysis
MSFT
27.01

INTC
21.75

MSFT
27.96

27.01

MSFT
31.21

27.96

21.75

from tick in ticks

group tick b...
Stock Trade Analysis
MSFT
27.01

INTC
21.75

MSFT
27.96

[27.01, 27.96]

MSFT
31.21

INTC
22.54

INTC
20.98

[27.96, 31.21...
Stock Trade Analysis
MSFT
27.01

INTC
21.75

MSFT
27.96

MSFT
31.21

0.034

INTC
22.54

INTC
20.98

0.104

MSFT
30.73

-0....
Stock Trade Analysis
MSFT
27.01

INTC
21.75

MSFT
27.96

MSFT
31.21

0.034

INTC
22.54

0.104

where diff > 0.1

MSFT
30.7...
Stock Trade Analysis
MSFT
27.01

INTC
21.75

MSFT
27.96

MSFT
31.21

INTC
22.54

Company = MSFT
Increase = 0.104
from tick...
Reactive Extensions Architecture

IScheduler
The Role of Schedulers
Parameterize Concurrency
//
// Runs a timer on the default scheduler
//
IObservable long
TimeSpan
/...
The Role of Schedulers
var

Observable.Return

Scheduler.ThreadPool
"Answer = "

xs.ObserveOn(
frm )
xs.ObserveOn(new Cont...
The IScheduler Interface
public interface IScheduler
{
DateTimeOffset Now { get; }
IDisposable Schedule<TState>( TState st...
Operational Layering of Rx
public static IObservable<T> Return<T>(T value,
IScheduler scheduler)
{
return Observable.Creat...
Virtualizing Time for Testing
var scheduler = new TestScheduler();
var input = scheduler.CreateHotObservable(
OnNext(300, ...
The Asynchronous Programming Landscape
Summary
• Tame your event streams using Rx and LINQ!
• Download Rx today!
– Through http://www.microsoft.com/download (sea...
Related Content
RxJS
/* Only get the value from each key up */
var keyups = Rx.Observable.fromEvent(input, 'keyup')
.selec...
ReactiveUI
public class NewUserViewModel : ReactiveObject
{
// This is ReactiveUI's version of implementing INotifyPropert...
Resources
• Channel 9
– Curing Your Event Processing Blues with Reactive Extensions (Rx) Bart De Smet
http://msdn.microsof...
Presenter contact details
c: +972-52-4772946
e: tamirdr@codevalue.net
b: TamirDresher.com
w: www.codevalue.net
Upcoming SlideShare
Loading in...5
×

Introduction to Reactive Extensions (Rx)

1,571

Published on

Presentations from the june meeting of IDNDUG

http://ariely.info/Communities/IDNDUG/IDNDUG19thJune2013/tabid/171


The Reactive Extensions (Rx) is a library for composing asynchronous and event-based programs using observable sequences and LINQ-style query operators. Using Rx, developers represent asynchronous data streams with Observables, query asynchronous data streams using LINQ operators, andparameterize the concurrency in the asynchronous data streams using Schedulers. Simply put, Rx = Observables + LINQ + Schedulers

Published in: Technology, Business
0 Comments
1 Like
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total Views
1,571
On Slideshare
0
From Embeds
0
Number of Embeds
1
Actions
Shares
0
Downloads
27
Comments
0
Likes
1
Embeds 0
No embeds

No notes for slide
  • העולם השתנה בשנים האחרונות והאפליקציות שאנחנו מפתחים היום צריכות להיות מחוברות להמון מקורות ולקבל מידע ממידע בורסאי וכלכלי שמתעדכן בתדירות גבוהה ועד לאירועי UI וEvents סביבתיים באופן כלליהמצב קשה עוד יותר כי צריך לעשות אגרגציות על כל הנתונים ולעשות פעולות שמערבות עוד נתונים ויותר מכך, כל שירות כזה חושף API משלו שאנחנו צריכים להתאים אליוRX בא בדיוק בשביל המטרה הזו ולתת בסיס אבסטרקטי שעליו נוכל להסתכל בשביל לעבוד מול כל המקורותבסופו של דבר RX הוא Events(sobservables)+LINQ+SchedulingRX
  • RX בנוי בצורה שכבתית (לפחות סכמטית)בבסיס יש לנו את המודל הConcurecy וה-timeמצד אחד פעולות שאנחנו עושים צריכות להתבצע במקום מסוים , בין אם thread או tasks ואפילו על גבי הענן מצד שני יש את עניין התזמון – יש שעון של המערכת, שעון dispatcher ואפילו שעון שמגיע מהרשתRX יודע לעשות אבסטרקציה לכל זהלמעלה יש לנו את צרות העבודה מול הEVENT שקורים כאשר LINQ מאפשר לנו לעשות טיפול פלואנטי עם כל היתרונות של LINQ ולהרכיב ולעשות אגרגציה על ובין אירועים. באמצע יש את הליבה שיודעת להסתכל על אירוע
  • Observbable הוא מה שמייצג את האירוע והוא הגורם אליו אנחנו נרשמים כדי לקבל את הנוטיפקציה שהאירוע התרחשObservers הם הדברים שמאזינים לאירוע
  • Transcript of "Introduction to Reactive Extensions (Rx)"

    1. 1. Reactive Extensions (RX) Tamir Dresher Senior Software Architect June 19, 2013 Slides: Bart De Smet
    2. 2. About Me • • • • • Software architect, consultant and instructor Technology addict 10 years of experience .NET and Native Windows Programming http://www.TamirDresher.com.
    3. 3. Applications And Data GPS RSS feeds Social media Server management
    4. 4. Recovery Projection Aggregating from quote in stock where quote.Symbol == “MSFT” select quote.Value IObservable<T> IScheduler Windowing Sampling Sharing Throttling Merging Joins Filtering Grouping Reactive Extensions Architecture Timeout ISubject<T> IObserver<T>
    5. 5. The building blocks • Observables – Producers (.NET events, WinRT Events, Sensors, APM method etc.) • Observers – Consumers Observable Subscribe Observer
    6. 6. Essential Interfaces namespace System { public interface IObservable<out T> { IDisposable Subscribe(IObserver<T> observer); } public interface IObserver<in T> { void OnNext(T value); void OnError(Exception error); void OnCompleted(); } }
    7. 7. Notification Grammar OnNext(42) OnNext(43) OnNext(“Hello”) OnNext OnCompleted OnError(error) OnError OnCompleted
    8. 8. Limitations of .NET Events exchange.StockTick += (sender, args) => { if (args.Quote.Symbol == “MSFT”) { // Imperative code } }; exchange.StockTick -= /* what goes here? */;
    9. 9. Observable Sequences to the Rescue IObservable<Quote> stockQuotes = …; var msft = stockQuotes .Where(quote => quote.Symbol == “MSFT”); var subscription = msft.Subscribe(quote => /* … */); subscription.Dispose();
    10. 10. Dictionary Suggest Asynchronous request React Dictionary web service Reaction Reactive Reactor Data binding on UI thread
    11. 11. Demo
    12. 12. Converting Events and Asynchronous Methods // Convert the TextChanged event to IObservable<string> var input = (from evt in Observable.FromEventPattern(txt, “TextChanged”) select ((TextBox)evt.Sender).Text) .Throttle(TimeSpan.FromSeconds(0.5)) .DistinctUntilChanged(); // Convert asynchronous proxy methods to Func<string, IObservable<string[]>> var lookup = Observable.FromAsyncPattern<string, string[]>(svc.BeginLookup, svc.EndLookup); // Compose both sources using a query var res = from term in input from words in lookup(term).TakeUntil(input) select words;
    13. 13. Stock Trade Analysis MSFT 27.01 INTC 21.75 from tick in ticks MSFT 27.96 MSFT 31.21 INTC 22.54 INTC 20.98 MSFT 30.73
    14. 14. Stock Trade Analysis MSFT 27.01 INTC 21.75 MSFT 27.96 27.01 MSFT 31.21 27.96 21.75 from tick in ticks group tick by tick.Symbol into company INTC 22.54 INTC 20.98 MSFT 30.73 30.73 31.21 22.54 20.98
    15. 15. Stock Trade Analysis MSFT 27.01 INTC 21.75 MSFT 27.96 [27.01, 27.96] MSFT 31.21 INTC 22.54 INTC 20.98 [27.96, 31.21] [31.21, 30.73] [21.75, 22.54] from tick in ticks group tick by tick.Symbol into company from openClose in company.Buffer(2, 1) MSFT 30.73 [22.54, 20.98]
    16. 16. Stock Trade Analysis MSFT 27.01 INTC 21.75 MSFT 27.96 MSFT 31.21 0.034 INTC 22.54 INTC 20.98 0.104 MSFT 30.73 -0.015 0.036 -0.069 from tick in ticks group tick by tick.Symbol into company from openClose in company.Buffer(2, 1) let diff = (openClose[1] – openClose[0]) / openClose[0]
    17. 17. Stock Trade Analysis MSFT 27.01 INTC 21.75 MSFT 27.96 MSFT 31.21 0.034 INTC 22.54 0.104 where diff > 0.1 MSFT 30.73 -0.015 0.036 from tick in ticks group tick by tick.Symbol into company from openClose in company.Buffer(2, 1) let diff = (openClose[1] – openClose[0]) / openClose[0] INTC 20.98 -0.069
    18. 18. Stock Trade Analysis MSFT 27.01 INTC 21.75 MSFT 27.96 MSFT 31.21 INTC 22.54 Company = MSFT Increase = 0.104 from tick in ticks group tick by tick.Symbol into company from openClose in company.Buffer(2, 1) let diff = (openClose[1] – openClose[0]) / openClose[0] where diff > 0.1 select new { Company = company.Key, Increase = diff } INTC 20.98 MSFT 30.73
    19. 19. Reactive Extensions Architecture IScheduler
    20. 20. The Role of Schedulers Parameterize Concurrency // // Runs a timer on the default scheduler // IObservable long TimeSpan // // Every operator that introduces concurrency // has an overload with an IScheduler // IObservable long TimeSpan IScheduler scheduler
    21. 21. The Role of Schedulers var Observable.Return Scheduler.ThreadPool "Answer = " xs.ObserveOn( frm ) xs.ObserveOn(new ControlScheduler(frm)) .Subscribe(x => lbl.Text = "Answer = " + x);
    22. 22. The IScheduler Interface public interface IScheduler { DateTimeOffset Now { get; } IDisposable Schedule<TState>( TState state, Func<IScheduler, TState, IDisposable> action); IDisposable Schedule<TState>( TimeSpan dueTime, TState state, Func<IScheduler, TState, IDisposable> action); IDisposable Schedule<TState>( DateTimeOffset dueTime, TState state, Func<IScheduler, TState, IDisposable> action); }
    23. 23. Operational Layering of Rx public static IObservable<T> Return<T>(T value, IScheduler scheduler) { return Observable.Create<T>(observer => { // Serialize state to scheduler; return ability to cancel return scheduler.Schedule(new { value, observer }, (_, x) => { x.observer.OnNext(x.value); x.observer.OnCompleted(); return Disposable.Empty; // No recursive work }); }); }
    24. 24. Virtualizing Time for Testing var scheduler = new TestScheduler(); var input = scheduler.CreateHotObservable( OnNext(300, “Bart De Smet”), OnNext(400, “Erik Meijer”), OnCompleted<string>(500) ); var results = scheduler.Start(() => from name in input select name.Length); results.Messages.AssertEqual( OnNext(300, 12), OnNext(400, 11), OnCompleted<int>(500) );
    25. 25. The Asynchronous Programming Landscape
    26. 26. Summary • Tame your event streams using Rx and LINQ! • Download Rx today! – Through http://www.microsoft.com/download (search for Rx SDK) – Using NuGet @ www.nuget.org (search for Rx-Main) • Watch videos at http://channel9.msdn.com/tags/Rx
    27. 27. Related Content RxJS /* Only get the value from each key up */ var keyups = Rx.Observable.fromEvent(input, 'keyup') .select(function (e) { return e.target.value; }) .where(function (text) { return text.length > 2; }); /* Now throttle/debounce the input for 500ms */ var throttled = keyups .throttle(500 /* ms */); /* Now get only distinct values, so we eliminate the arrows */ var distinct = keyups .distinctUntilChanged(); RX++ void PrintPrimes(int n) { std::cout<<"Rx: first "<<n<<" primes squared"<<endl; auto values = rxcpp::Range(2); rxcpp::from(values) .where(IsPrime) .select([](int x) { return std::make_pair(x, x*x); }) .take(n) .for_each(rxcpp::MakeTupleDispatch( [](int p, int s) { cout<<p<<" =square=> "<<s<<endl; })); }
    28. 28. ReactiveUI public class NewUserViewModel : ReactiveObject { // This is ReactiveUI's version of implementing INotifyPropertyChanged string _Password,_PasswordConfirmation; public string Password { get { return _Password; } set { this.RaiseAndSetIfChanged(x => x.Password, value); } } public string PasswordConfirmation { get { return _PasswordConfirmation; } set { this.RaiseAndSetIfChanged(x => x.PasswordConfirmation, value); } } ICommand OkCommand { get; protected set; } public NewUserViewModel() { var canHitOk = this.WhenAny( x => x.Password, x => x.PasswordConfirmation, (pass, confirm) => (pass.Value == confirm.Value && pass.Value.Length > 3)); OkCommand = new ReactiveCommand(canHitOk); } 28
    29. 29. Resources • Channel 9 – Curing Your Event Processing Blues with Reactive Extensions (Rx) Bart De Smet http://msdn.microsoft.com/enus/library/windowsazure/jj860549.aspx • IntroToRx.com – IntroToRx.com is the online resource for getting started with the Reactive Extensions to .Net. • www.reactiveui.com https://github.com/reactiveui/ReactiveUI.Samples
    30. 30. Presenter contact details c: +972-52-4772946 e: tamirdr@codevalue.net b: TamirDresher.com w: www.codevalue.net
    1. A particular slide catching your eye?

      Clipping is a handy way to collect important slides you want to go back to later.

    ×