SlideShare ist ein Scribd-Unternehmen logo
1 von 30
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 Windows Programming
http://www.TamirDresher.com.
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>

IScheduler

Windowing
Sampling
Sharing
Throttling
Merging

Joins

Filtering
Grouping

Reactive Extensions Architecture

Timeout

ISubject<T>

IObserver<T>
The building blocks
‱ Observables
– Producers (.NET events, WinRT Events, Sensors, APM method etc.)

‱ Observers
– Consumers

Observable
Subscribe

Observer
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();
}
}
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
}
};
exchange.StockTick -= /* what goes here? */;
Observable Sequences to the Rescue
IObservable<Quote> stockQuotes = 
;
var msft = stockQuotes

.Where(quote => quote.Symbol == “MSFT”);
var subscription = msft.Subscribe(quote => /* 
 */);

subscription.Dispose();
Dictionary Suggest
Asynchronous
request
React

Dictionary web
service

Reaction
Reactive
Reactor

Data binding
on UI thread
Demo
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;
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
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
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]
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]
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
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
Reactive Extensions Architecture

IScheduler
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
The Role of Schedulers
var

Observable.Return

Scheduler.ThreadPool
"Answer = "

xs.ObserveOn(
frm )
xs.ObserveOn(new ControlScheduler(frm))
.Subscribe(x => lbl.Text = "Answer = " + x);
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);
}
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
});
});
}
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)
);
The Asynchronous Programming Landscape
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
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;
}));
}
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
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
Presenter contact details
c: +972-52-4772946
e: tamirdr@codevalue.net
b: TamirDresher.com
w: www.codevalue.net

Weitere Àhnliche Inhalte

Was ist angesagt?

Tieto tdd from-dreams_to_reality_s.narkevicius_v.pozdniakov_2013 (1)
Tieto tdd from-dreams_to_reality_s.narkevicius_v.pozdniakov_2013 (1)Tieto tdd from-dreams_to_reality_s.narkevicius_v.pozdniakov_2013 (1)
Tieto tdd from-dreams_to_reality_s.narkevicius_v.pozdniakov_2013 (1)
Agile Lietuva
 
Advanced Java Practical File
Advanced Java Practical FileAdvanced Java Practical File
Advanced Java Practical File
Soumya Behera
 
Swiss army knife Spring
Swiss army knife SpringSwiss army knife Spring
Swiss army knife Spring
Mario Fusco
 

Was ist angesagt? (20)

Base de-datos
Base de-datosBase de-datos
Base de-datos
 
Java_practical_handbook
Java_practical_handbookJava_practical_handbook
Java_practical_handbook
 
Spock framework
Spock frameworkSpock framework
Spock framework
 
New Java Date/Time API
New Java Date/Time APINew Java Date/Time API
New Java Date/Time API
 
Tieto tdd from-dreams_to_reality_s.narkevicius_v.pozdniakov_2013 (1)
Tieto tdd from-dreams_to_reality_s.narkevicius_v.pozdniakov_2013 (1)Tieto tdd from-dreams_to_reality_s.narkevicius_v.pozdniakov_2013 (1)
Tieto tdd from-dreams_to_reality_s.narkevicius_v.pozdniakov_2013 (1)
 
Rxjs ppt
Rxjs pptRxjs ppt
Rxjs ppt
 
Java Performance Puzzlers
Java Performance PuzzlersJava Performance Puzzlers
Java Performance Puzzlers
 
Java practical
Java practicalJava practical
Java practical
 
Java PRACTICAL file
Java PRACTICAL fileJava PRACTICAL file
Java PRACTICAL file
 
Rx for Android & iOS by Harin Trivedi
Rx for Android & iOS  by Harin TrivediRx for Android & iOS  by Harin Trivedi
Rx for Android & iOS by Harin Trivedi
 
Hadoop Puzzlers
Hadoop PuzzlersHadoop Puzzlers
Hadoop Puzzlers
 
Spock Framework
Spock FrameworkSpock Framework
Spock Framework
 
Reactive programming with RxAndroid
Reactive programming with RxAndroidReactive programming with RxAndroid
Reactive programming with RxAndroid
 
Tools and Techniques for Understanding Threading Behavior in Android*
Tools and Techniques for Understanding Threading Behavior in Android*Tools and Techniques for Understanding Threading Behavior in Android*
Tools and Techniques for Understanding Threading Behavior in Android*
 
Art of unit testing: How developer should care about code quality
Art of unit testing: How developer should care about code qualityArt of unit testing: How developer should care about code quality
Art of unit testing: How developer should care about code quality
 
JVM Mechanics
JVM MechanicsJVM Mechanics
JVM Mechanics
 
Rxjs vienna
Rxjs viennaRxjs vienna
Rxjs vienna
 
Advanced Java Practical File
Advanced Java Practical FileAdvanced Java Practical File
Advanced Java Practical File
 
Machine Learning Model Bakeoff
Machine Learning Model BakeoffMachine Learning Model Bakeoff
Machine Learning Model Bakeoff
 
Swiss army knife Spring
Swiss army knife SpringSwiss army knife Spring
Swiss army knife Spring
 

Ähnlich wie Introduction to Reactive Extensions (Rx)

Georgy Nosenko - An introduction to the use SMT solvers for software security
Georgy Nosenko - An introduction to the use SMT solvers for software securityGeorgy Nosenko - An introduction to the use SMT solvers for software security
Georgy Nosenko - An introduction to the use SMT solvers for software security
DefconRussia
 
Windows Remote Management - EN
Windows Remote Management - ENWindows Remote Management - EN
Windows Remote Management - EN
Kirill Nikolaev
 
Advanced iOS Build Mechanics, Sebastien Pouliot
Advanced iOS Build Mechanics, Sebastien PouliotAdvanced iOS Build Mechanics, Sebastien Pouliot
Advanced iOS Build Mechanics, Sebastien Pouliot
Xamarin
 
22-4_PerformanceTuningUsingtheAdvisorFramework.pdf
22-4_PerformanceTuningUsingtheAdvisorFramework.pdf22-4_PerformanceTuningUsingtheAdvisorFramework.pdf
22-4_PerformanceTuningUsingtheAdvisorFramework.pdf
yishengxi
 

Ähnlich wie Introduction to Reactive Extensions (Rx) (20)

Georgy Nosenko - An introduction to the use SMT solvers for software security
Georgy Nosenko - An introduction to the use SMT solvers for software securityGeorgy Nosenko - An introduction to the use SMT solvers for software security
Georgy Nosenko - An introduction to the use SMT solvers for software security
 
Ekon25 mORMot 2 Server-Side Notifications
Ekon25 mORMot 2 Server-Side NotificationsEkon25 mORMot 2 Server-Side Notifications
Ekon25 mORMot 2 Server-Side Notifications
 
SQL Performance Tuning and New Features in Oracle 19c
SQL Performance Tuning and New Features in Oracle 19cSQL Performance Tuning and New Features in Oracle 19c
SQL Performance Tuning and New Features in Oracle 19c
 
Performance is a Feature! at DDD 11
Performance is a Feature! at DDD 11Performance is a Feature! at DDD 11
Performance is a Feature! at DDD 11
 
With big data comes big responsibility
With big data comes big responsibilityWith big data comes big responsibility
With big data comes big responsibility
 
Where the wild things are - Benchmarking and Micro-Optimisations
Where the wild things are - Benchmarking and Micro-OptimisationsWhere the wild things are - Benchmarking and Micro-Optimisations
Where the wild things are - Benchmarking and Micro-Optimisations
 
Windows Remote Management - EN
Windows Remote Management - ENWindows Remote Management - EN
Windows Remote Management - EN
 
Performance and how to measure it - ProgSCon London 2016
Performance and how to measure it - ProgSCon London 2016Performance and how to measure it - ProgSCon London 2016
Performance and how to measure it - ProgSCon London 2016
 
Performance is a Feature!
Performance is a Feature!Performance is a Feature!
Performance is a Feature!
 
New Zephyr features: LWM2M / FOTA Framework - SFO17-113
New Zephyr features: LWM2M / FOTA Framework - SFO17-113New Zephyr features: LWM2M / FOTA Framework - SFO17-113
New Zephyr features: LWM2M / FOTA Framework - SFO17-113
 
Tdd,Ioc
Tdd,IocTdd,Ioc
Tdd,Ioc
 
Advanced iOS Build Mechanics, Sebastien Pouliot
Advanced iOS Build Mechanics, Sebastien PouliotAdvanced iOS Build Mechanics, Sebastien Pouliot
Advanced iOS Build Mechanics, Sebastien Pouliot
 
PMED Undergraduate Workshop - R Tutorial for PMED Undegraduate Workshop - Xi...
PMED Undergraduate Workshop - R Tutorial for PMED Undegraduate Workshop  - Xi...PMED Undergraduate Workshop - R Tutorial for PMED Undegraduate Workshop  - Xi...
PMED Undergraduate Workshop - R Tutorial for PMED Undegraduate Workshop - Xi...
 
Observability and its application
Observability and its applicationObservability and its application
Observability and its application
 
Apache Flink: API, runtime, and project roadmap
Apache Flink: API, runtime, and project roadmapApache Flink: API, runtime, and project roadmap
Apache Flink: API, runtime, and project roadmap
 
22-4_PerformanceTuningUsingtheAdvisorFramework.pdf
22-4_PerformanceTuningUsingtheAdvisorFramework.pdf22-4_PerformanceTuningUsingtheAdvisorFramework.pdf
22-4_PerformanceTuningUsingtheAdvisorFramework.pdf
 
Software Engineering
Software EngineeringSoftware Engineering
Software Engineering
 
Learning Dtrace
Learning DtraceLearning Dtrace
Learning Dtrace
 
Reactive Stream Processing Using DDS and Rx
Reactive Stream Processing Using DDS and RxReactive Stream Processing Using DDS and Rx
Reactive Stream Processing Using DDS and Rx
 
Capacity Planning for Linux Systems
Capacity Planning for Linux SystemsCapacity Planning for Linux Systems
Capacity Planning for Linux Systems
 

Mehr von Tamir Dresher

Mehr von Tamir Dresher (20)

NET Aspire - NET Conf IL 2024 - Tamir Dresher.pdf
NET Aspire - NET Conf IL 2024 - Tamir Dresher.pdfNET Aspire - NET Conf IL 2024 - Tamir Dresher.pdf
NET Aspire - NET Conf IL 2024 - Tamir Dresher.pdf
 
Tamir Dresher - DotNet 7 What's new.pptx
Tamir Dresher - DotNet 7 What's new.pptxTamir Dresher - DotNet 7 What's new.pptx
Tamir Dresher - DotNet 7 What's new.pptx
 
Tamir Dresher - What’s new in ASP.NET Core 6
Tamir Dresher - What’s new in ASP.NET Core 6Tamir Dresher - What’s new in ASP.NET Core 6
Tamir Dresher - What’s new in ASP.NET Core 6
 
Tamir Dresher - Async Streams in C#
Tamir Dresher - Async Streams in C#Tamir Dresher - Async Streams in C#
Tamir Dresher - Async Streams in C#
 
Anatomy of a data driven architecture - Tamir Dresher
Anatomy of a data driven architecture - Tamir Dresher   Anatomy of a data driven architecture - Tamir Dresher
Anatomy of a data driven architecture - Tamir Dresher
 
Tamir Dresher Clarizen adventures with the wild GC during the holiday season
Tamir Dresher   Clarizen adventures with the wild GC during the holiday seasonTamir Dresher   Clarizen adventures with the wild GC during the holiday season
Tamir Dresher Clarizen adventures with the wild GC during the holiday season
 
Debugging tricks you wish you knew Tamir Dresher - Odessa 2019
Debugging tricks you wish you knew   Tamir Dresher - Odessa 2019Debugging tricks you wish you knew   Tamir Dresher - Odessa 2019
Debugging tricks you wish you knew Tamir Dresher - Odessa 2019
 
From zero to hero with the actor model - Tamir Dresher - Odessa 2019
From zero to hero with the actor model  - Tamir Dresher - Odessa 2019From zero to hero with the actor model  - Tamir Dresher - Odessa 2019
From zero to hero with the actor model - Tamir Dresher - Odessa 2019
 
Tamir Dresher - Demystifying the Core of .NET Core
Tamir Dresher  - Demystifying the Core of .NET CoreTamir Dresher  - Demystifying the Core of .NET Core
Tamir Dresher - Demystifying the Core of .NET Core
 
Breaking the monolith to microservice with Docker and Kubernetes (k8s)
Breaking the monolith to microservice with Docker and Kubernetes (k8s)Breaking the monolith to microservice with Docker and Kubernetes (k8s)
Breaking the monolith to microservice with Docker and Kubernetes (k8s)
 
.Net december 2017 updates - Tamir Dresher
.Net december 2017 updates - Tamir Dresher.Net december 2017 updates - Tamir Dresher
.Net december 2017 updates - Tamir Dresher
 
Testing time and concurrency Rx
Testing time and concurrency RxTesting time and concurrency Rx
Testing time and concurrency Rx
 
.NET Debugging tricks you wish you knew tamir dresher
.NET Debugging tricks you wish you knew   tamir dresher.NET Debugging tricks you wish you knew   tamir dresher
.NET Debugging tricks you wish you knew tamir dresher
 
From Zero to the Actor Model (With Akka.Net) - CodeMash2017 - Tamir Dresher
From Zero to the Actor Model (With Akka.Net) - CodeMash2017 - Tamir DresherFrom Zero to the Actor Model (With Akka.Net) - CodeMash2017 - Tamir Dresher
From Zero to the Actor Model (With Akka.Net) - CodeMash2017 - Tamir Dresher
 
Debugging tricks you wish you knew - Tamir Dresher
Debugging tricks you wish you knew  - Tamir DresherDebugging tricks you wish you knew  - Tamir Dresher
Debugging tricks you wish you knew - Tamir Dresher
 
Rx 101 - Tamir Dresher - Copenhagen .NET User Group
Rx 101  - Tamir Dresher - Copenhagen .NET User GroupRx 101  - Tamir Dresher - Copenhagen .NET User Group
Rx 101 - Tamir Dresher - Copenhagen .NET User Group
 
Cloud patterns - NDC Oslo 2016 - Tamir Dresher
Cloud patterns - NDC Oslo 2016 - Tamir DresherCloud patterns - NDC Oslo 2016 - Tamir Dresher
Cloud patterns - NDC Oslo 2016 - Tamir Dresher
 
Reactiveness All The Way - SW Architecture 2015 Conference
Reactiveness All The Way - SW Architecture 2015 ConferenceReactiveness All The Way - SW Architecture 2015 Conference
Reactiveness All The Way - SW Architecture 2015 Conference
 
Leveraging Dependency Injection(DI) in Universal Applications - Tamir Dresher
Leveraging Dependency Injection(DI) in Universal Applications -  Tamir DresherLeveraging Dependency Injection(DI) in Universal Applications -  Tamir Dresher
Leveraging Dependency Injection(DI) in Universal Applications - Tamir Dresher
 
Where Is My Data - ILTAM Session
Where Is My Data - ILTAM SessionWhere Is My Data - ILTAM Session
Where Is My Data - ILTAM Session
 

KĂŒrzlich hochgeladen

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 

KĂŒrzlich hochgeladen (20)

2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 

Introduction to Reactive Extensions (Rx)

  • 1. Reactive Extensions (RX) Tamir Dresher Senior Software Architect June 19, 2013 Slides: Bart De Smet
  • 2. About Me ‱ ‱ ‱ ‱ ‱ Software architect, consultant and instructor Technology addict 10 years of experience .NET and Native Windows Programming http://www.TamirDresher.com.
  • 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. The building blocks ‱ Observables – Producers (.NET events, WinRT Events, Sensors, APM method etc.) ‱ Observers – Consumers Observable Subscribe Observer
  • 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(); } }
  • 8. Limitations of .NET Events exchange.StockTick += (sender, args) => { if (args.Quote.Symbol == “MSFT”) { // Imperative code } }; exchange.StockTick -= /* what goes here? */;
  • 9. Observable Sequences to the Rescue IObservable<Quote> stockQuotes = 
; var msft = stockQuotes .Where(quote => quote.Symbol == “MSFT”); var subscription = msft.Subscribe(quote => /* 
 */); subscription.Dispose();
  • 11. Demo
  • 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. 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. 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. 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. 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. 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. 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
  • 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. 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. 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. 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. 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) );
  • 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. 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. 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. 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. Presenter contact details c: +972-52-4772946 e: tamirdr@codevalue.net b: TamirDresher.com w: www.codevalue.net

Hinweis der Redaktion

  1. Ś”ŚąŚ•ŚœŚ Ś”Ś©ŚȘŚ Ś” Ś‘Ś©Ś Ś™Ś Ś”ŚŚ—ŚšŚ•Ś Ś•ŚȘ Ś•Ś”ŚŚ€ŚœŚ™Ś§ŚŠŚ™Ś•ŚȘ Ś©ŚŚ Ś—Ś Ś• ŚžŚ€ŚȘŚ—Ś™Ś Ś”Ś™Ś•Ś ŚŠŚšŚ™Ś›Ś•ŚȘ ŚœŚ”Ś™Ś•ŚȘ ŚžŚ—Ś•Ś‘ŚšŚ•ŚȘ ŚœŚ”ŚžŚ•ŚŸ ŚžŚ§Ś•ŚšŚ•ŚȘ Ś•ŚœŚ§Ś‘Śœ ŚžŚ™Ś“Śą ŚžŚžŚ™Ś“Śą Ś‘Ś•ŚšŚĄŚŚ™ Ś•Ś›ŚœŚ›ŚœŚ™ Ś©ŚžŚȘŚąŚ“Ś›ŚŸ Ś‘ŚȘŚ“Ś™ŚšŚ•ŚȘ Ś’Ś‘Ś•Ś”Ś” Ś•ŚąŚ“ ŚœŚŚ™ŚšŚ•ŚąŚ™ UI Ś•Events ŚĄŚ‘Ś™Ś‘ŚȘŚ™Ś™Ś Ś‘ŚŚ•Ś€ŚŸ Ś›ŚœŚœŚ™Ś”ŚžŚŠŚ‘ Ś§Ś©Ś” ŚąŚ•Ś“ Ś™Ś•ŚȘŚš Ś›Ś™ ŚŠŚšŚ™Śš ŚœŚąŚ©Ś•ŚȘ ŚŚ’ŚšŚ’ŚŠŚ™Ś•ŚȘ ŚąŚœ Ś›Śœ Ś”Ś ŚȘŚ•Ś Ś™Ś Ś•ŚœŚąŚ©Ś•ŚȘ Ś€ŚąŚ•ŚœŚ•ŚȘ Ś©ŚžŚąŚšŚ‘Ś•ŚȘ ŚąŚ•Ś“ Ś ŚȘŚ•Ś Ś™Ś Ś•Ś™Ś•ŚȘŚš ŚžŚ›Śš, Ś›Śœ Ś©Ś™ŚšŚ•ŚȘ Ś›Ś–Ś” Ś—Ś•Ś©ŚŁ API ŚžŚ©ŚœŚ• Ś©ŚŚ Ś—Ś Ś• ŚŠŚšŚ™Ś›Ś™Ś ŚœŚ”ŚȘŚŚ™Ś ŚŚœŚ™Ś•RX Ś‘Ś Ś‘Ś“Ś™Ś•Ś§ Ś‘Ś©Ś‘Ś™Śœ Ś”ŚžŚ˜ŚšŚ” Ś”Ś–Ś• Ś•ŚœŚȘŚȘ Ś‘ŚĄŚ™ŚĄ ŚŚ‘ŚĄŚ˜ŚšŚ§Ś˜Ś™ Ś©ŚąŚœŚ™Ś• Ś Ś•Ś›Śœ ŚœŚ”ŚĄŚȘŚ›Śœ Ś‘Ś©Ś‘Ś™Śœ ŚœŚąŚ‘Ś•Ś“ ŚžŚ•Śœ Ś›Śœ Ś”ŚžŚ§Ś•ŚšŚ•ŚȘŚ‘ŚĄŚ•Ś€Ś• Ś©Śœ Ś“Ś‘Śš RX Ś”Ś•Ś Events(sobservables)+LINQ+SchedulingRX
  2. RX Ś‘Ś Ś•Ś™ Ś‘ŚŠŚ•ŚšŚ” Ś©Ś›Ś‘ŚȘŚ™ŚȘ (ŚœŚ€Ś—Ś•ŚȘ ŚĄŚ›ŚžŚ˜Ś™ŚȘ)Ś‘Ś‘ŚĄŚ™ŚĄ Ś™Ś© ŚœŚ Ś• ŚŚȘ Ś”ŚžŚ•Ś“Śœ Ś”Concurecy Ś•Ś”-timeŚžŚŠŚ“ ŚŚ—Ś“ Ś€ŚąŚ•ŚœŚ•ŚȘ Ś©ŚŚ Ś—Ś Ś• ŚąŚ•Ś©Ś™Ś ŚŠŚšŚ™Ś›Ś•ŚȘ ŚœŚ”ŚȘŚ‘ŚŠŚą Ś‘ŚžŚ§Ś•Ś ŚžŚĄŚ•Ś™Ś , Ś‘Ś™ŚŸ ŚŚ thread ŚŚ• tasks Ś•ŚŚ€Ś™ŚœŚ• ŚąŚœ Ś’Ś‘Ś™ Ś”ŚąŚ ŚŸ ŚžŚŠŚ“ Ś©Ś Ś™ Ś™Ś© ŚŚȘ ŚąŚ Ś™Ś™ŚŸ Ś”ŚȘŚ–ŚžŚ•ŚŸ – Ś™Ś© Ś©ŚąŚ•ŚŸ Ś©Śœ Ś”ŚžŚąŚšŚ›ŚȘ, Ś©ŚąŚ•ŚŸ dispatcher Ś•ŚŚ€Ś™ŚœŚ• Ś©ŚąŚ•ŚŸ Ś©ŚžŚ’Ś™Śą ŚžŚ”ŚšŚ©ŚȘRX Ś™Ś•Ś“Śą ŚœŚąŚ©Ś•ŚȘ ŚŚ‘ŚĄŚ˜ŚšŚ§ŚŠŚ™Ś” ŚœŚ›Śœ Ś–Ś”ŚœŚžŚąŚœŚ” Ś™Ś© ŚœŚ Ś• ŚŚȘ ŚŠŚšŚ•ŚȘ Ś”ŚąŚ‘Ś•Ś“Ś” ŚžŚ•Śœ Ś”EVENT Ś©Ś§Ś•ŚšŚ™Ś Ś›ŚŚ©Śš LINQ ŚžŚŚ€Ś©Śš ŚœŚ Ś• ŚœŚąŚ©Ś•ŚȘ Ś˜Ś™Ś€Ś•Śœ Ś€ŚœŚ•ŚŚ Ś˜Ś™ ŚąŚ Ś›Śœ Ś”Ś™ŚȘŚšŚ•Ś Ś•ŚȘ Ś©Śœ LINQ Ś•ŚœŚ”ŚšŚ›Ś™Ś‘ Ś•ŚœŚąŚ©Ś•ŚȘ ŚŚ’ŚšŚ’ŚŠŚ™Ś” ŚąŚœ Ś•Ś‘Ś™ŚŸ ŚŚ™ŚšŚ•ŚąŚ™Ś. Ś‘ŚŚžŚŠŚą Ś™Ś© ŚŚȘ Ś”ŚœŚ™Ś‘Ś” Ś©Ś™Ś•Ś“ŚąŚȘ ŚœŚ”ŚĄŚȘŚ›Śœ ŚąŚœ ŚŚ™ŚšŚ•Śą
  3. Observbable Ś”Ś•Ś ŚžŚ” Ś©ŚžŚ™Ś™ŚŠŚ’ ŚŚȘ Ś”ŚŚ™ŚšŚ•Śą Ś•Ś”Ś•Ś Ś”Ś’Ś•ŚšŚ ŚŚœŚ™Ś• ŚŚ Ś—Ś Ś• Ś ŚšŚ©ŚžŚ™Ś Ś›Ś“Ś™ ŚœŚ§Ś‘Śœ ŚŚȘ Ś”Ś Ś•Ś˜Ś™Ś€Ś§ŚŠŚ™Ś” Ś©Ś”ŚŚ™ŚšŚ•Śą Ś”ŚȘŚšŚ—Ś©Observers Ś”Ś Ś”Ś“Ś‘ŚšŚ™Ś Ś©ŚžŚŚ–Ś™Ś Ś™Ś ŚœŚŚ™ŚšŚ•Śą