SlideShare a Scribd company logo
1 of 25
Understanding reactive programming
with Microsoft Reactive Extensions
Oleksandr Zhevzhyk, 2017
WHY REACTIVE?
● Have a curious interface (-= and +=)
● Are difficult to compose
● Don't offer the ability to be easily queried over time
● Provide almost no help for concurrency or multithreaded applications
● No blocking while waiting for a result
● The result is pushed to you when it is ready
● Developers need tools to react to pushed data
EVENTS
● Have nothing to do with events
● Handling exceptions, cancellation and synchronization is difficult
● Much better that events, but still difficult to compose
TASKS
REACTIVE IS THE NEW BLACK
REACTIVE PROGRAMMING IS PROGRAMMING WITH ASYNCHRONOUS DATA STREAMS
RX: HELPFUL RESOURCES
GitHub
https://github.com/Reactive-Extensions
NuGet
System.Reactive (main library)
> Install-Package System.Reactive
MSDN
https://msdn.microsoft.com/library/hh242985.aspx
“Intro to Rx” by Lee Campbell
http://introtorx.com
Online / Kindle / EPUBStack Overflow
system.reactive tag
http://stackoverflow.com/questions/tagged/system.reactive
RX: IMPLEMENTATIONS
Rx.NET - Reactive Extensions for .NET
RxJS - Reactive Extensions for JavaScript
RxJS-ExtJS - Ext JS Bindings for RxJS
rx.angular.js - AngularJS Bindings for RxJS
RxJS-DOM - HTML DOM Bindings for RxJS
RxCpp - Reactive Extensions for C++
Rx.ObjC - Reactive Extensions for Objective C
RxPy - Reactive Extensions for Python
WHAT IS RX?
Rx is a library for composing asynchronous and event-based programs using
observable sequences and LINQ-style query operators.
With Rx you:
- represent asynchronous data streams with Observables
- query asynchronous data streams using LINQ operators
- control the concurrency in the asynchronous data streams using Schedulers.
Rx = Observables + LINQ + Schedulers
OnNext* (OnCompleted | OnError)?
OBSERVABLE: GRAMMAR
OBSERVABLE: CORE INTERFACES
IObservable<T>
.Subscribe (
Action<T> onNext,
Action<Exception> onError,
Action onCompleted)
IObserver<T>
.OnNext (T value)
.OnCompleted ()
.OnError(Exception ex)
IObservable<string> namesObservable = ...;
namesObservable.Subscribe(
name => this.List.Add(name),
ex => this.LogService.LogException(ex);
() => this.RaiseNamesReady(EventArgs.Empty));
OBSERVABLE: CHAIN
OBSERVABLE: FACTORIES#1
Observable.Never<int>():
∅
Observable.Empty<bool>():
OnCompleted
Observable.Generate(1, x => x < 6, x => x + 2, x => x*x):
1 → 9 → 25 → OnCompleted
Observable.Throw<float>():
OnError
Observable.Return(“abc”):
“abc” → OnCompleted
OBSERVABLE: FACTORIES#2
ConsoleCancelEventArgs → ConsoleCancelEventArgs → … (∞)
Observable.FromEventPattern<ConsoleCancelEventHandler,
ConsoleCancelEventArgs>(
h => Console.CancelKeyPress += h,
h => Console.CancelKeyPress -= h);
var fileStream = new FileStream(file, FileMode.Open);
var observableFactory = Observable.FromAsyncPattern<byte[], int, int, int>(
fileStream.BeginRead,
fileStream.EndRead);
var bytes = new byte[fileStream.Length];
observableFactory(bytes, 0, fileStream.Length)
.Subscribe(actualRead => { /*process bytes*/ });
actualRead → OnCompleted
FROM
APM
FROM
EVENT
OBSERVABLE: FACTORIES#3
Observable.FromAsync(() =>
Task.Factory.StartNew(() =>
{
Thread.Sleep(5000);
return "404";
}));
FROM
TASK
“404” → OnCompleted
Observable.Using(
() => new FileStream(@"C:movie.mkv", FileMode.Open),
fs => this.ReadFileObservable(fs));
FROM
IDISPOSABLE
OBSERVABLE: FACTORIES#4
Bob → Bill → Alice → OnCompleted
var names = Observable.Create<string>(
observer =>
{
observer.OnNext("Bob");
observer.OnNext("Bill");
observer.OnNext("Alice");
observer.OnCompleted();
return Disposable.Empty;
});
Not asynchronous
Not cancellable
var observable = Observable.Create<int>(observer => {
var cd = new CancellationDisposable();
var pause = TimeSpan.FromSeconds(3);
int counter = 0;
Action action = () => {
if (!cd.Token.IsCancellationRequested) {
observer.OnNext(++counter);
if (counter == 5)
observer.OnCompleted();
else
scheduler.Schedule(pause, action);
}
};
scheduler.Schedule(action);
return cd;
});
1 → 2 → 3 → 4 → 5 → OnCompleted
OBSERVABLE: CANCELLATION
Subscribe() returns an IDisposable. Keep it.
public void Initialize()
{
this._updateUriDisposable = Observable
.FromEventPattern<EventHandler<UriChangedEventArgs>, UriChangedEventArgs>(
h => this.Options.UriChanged += h,
h => this.Options.UriChanged -= h)
.SelectMany(args => this.RestRequestService.Get(args.EventArgs.Uri, Scheduler.ThreadPool))
.ObserveOn(this.Dispatcher)
.Subscribe(
response => this.WebView.Update(response),
ex => this.HandleError(ex));
}
public void Close() { this._updateUriDisposable.Dispose(); }
Call Dispose on it to stop the Observable.
OBSERVABLE: CLEANUP
RX IS TIDY WHEN
Observable has finished with
OnCompleted or OnError
Observable was manually
stopped by Disposable
var changedDisposable = Observable.FromEventPattern(model, nameof(model.Changed))
.Finally(() => Console.WriteLine("Disposed!"))
.Subscribe();
//...
changedDisposable.Dispose();
Use Finally()
when you want
to track disposal
of the data stream
LINQ: OVERVIEW
- projection
- filtering
- aggregation
- composing
- time-based operations
You could think:
RX is LINQ to events
LINQ: FILTERING
Where
Take / TakeWhile
Skip / SkipWhile
FirstAsync
LastAsync
Observable
.FromEventPattern(
h => textBox.KeyPress += h,
h => textBox.KeyPress -= h)
.Where(_ => _.EventArgs.KeyCode == Keys.Enter)
.Skip(10)
.Take(3)
.FirstAsync()
.Subscribe(_ => { });
EventPattern → OnCompleted
LINQ: PROJECTION
Select
Observable.Return(100)
.Select(num => num.ToString())
.Subscribe(str => Console.Write(str));
IObservable<T1> → IObservable<T2>
Select + Switch
SelectMany observable123.SelectMany(num => observableABCD)
observable123.Select(n => observableABCD).Switch()
IObservable<T1> → IObservable<IObservable<T2>>
LINQ: PROJECTION#SELECT MANY
observable123
.SelectMany(num => observableABCD)
.Subscribe(letter => Console.WriteLine(letter));
LINQ: PROJECTION#SELECT+SWITCH
observable123
.Select(num => observableABCD)
.Switch()
.Subscribe(letter => Console.WriteLine(letter));
LINQ: AGGREGATION
ToArray
GroupBy
Aggregate
All
Any
observable123.ToArray().Subscribe(array => { });
[1, 2, 3] → OnCompleted
All aggregation functions produce
an observable with an aggregated result!
...
observable123
.SelectMany(num => observableABCD)
.GroupBy(l => l)
.Subscribe(grouped => grouped
.Aggregate("", (l, res) => res + l)
.Subscribe(aggr => { }));
“AAA” → “BBB” → “CCC” → “DDD” → OnCompleted
LINQ: COMPOSING
Fork/Join
Observable
.When(observableABCD
.And(observable123)
.Then((l, n) =>
new {Letter = l, Number = n}))
.Subscribe(pair => { });
{“A”, 1} → {“B”,2} → {“C”,3} → OnCompleted
CombineLatest
Observable
.CombineLatest(
observable123,
observableABCD,
(l, n) => new { Letter = l, Number = n })
.Subscribe();
{“C”, 1} → {“C”,2} → {“D”,2} → {“D”,3} → OnCompleted
Merge
observable123.Merge(observable789).Subscribe(n => { });
1 → 7 → 2 → 3 → 8 → 9 → OnCompleted
Concat
1 → 2 → 3 → 7 → 8 → 9 → OnCompleted
observable123.Concat(observable789).Subscribe(n => { });
SkipUntil / TakeUntil
observable123
.SkipUntil(observable789)
.Subscribe(n => { });
1 → 2 → OnCompleted
RX: SCHEDULERS
By default: single threaded.
IScheduler
Scheduler.CurrentThread
Scheduler.ThreadPool DispatcherScheduler
TestScheduler
- Some Rx methods accept IScheduler
Observable
.Return(“data”, Scheduler.ThreadPool)
.Subscribe(_ => {/*worker thread*/});
- ObserveOn method
observable123
.ObserveOn(Scheduler.ThreadPool)
.Select(n => n.ToString())
.ObserveOn(this.Dispatcher)
.Subscribe(s => { })
EXCEPTION HANDLING
Everything what happens in Observable stays in Observable.
Besides onNext/onCompleted in Subscribe!
observable123
.SelectMany(n =>
Observable.When(observableABCD
.And(observableXY)
.Then((l1, l2) => l1 + l2))
.Select(word => ProccessWord(word)))
.Subscribe(_ => { }, ex => { });
Exception!
Exception!
Exception!
_restService.Get(uri, Scheduler.ThreadPool)
.Catch<RestException>(
ex => Observable.Return("[]"))
.Subscribe(data => { });
Swallowing exceptions with Catch method
FIELD EXAMPLE
Refresh event
UriChanged event
Closed event
3 async web requests
public IObservable<JArray> DataObservable(Uri uri, string resource)
{
return RestRequestService
.Get(Scheduler.ThreadPool, Options.Uri, resource)
.Catch<RestException>(ex =>
{
this.LogService.LogException(ex);
return "[]";
})
.Select(json => Json.Parse(json));
}
uriChanged.Merge(refreshRequested)
.Do(_ => this.IsBusy = true)
.Select(opt => Observable
.When(this.DataObservable(opt.Uri, "cars")
.And(this.DataObservable(opt.Uri, "trams")
.And(this.DataObservable(opt.Uri, "planes"))
.Then((cars, trams, planes) =>
this.CreateDataModel(cars, trams, planes)))))
.Switch()
.TakeUntil(closeRequested)
.ObserveOn(this.Dispatcher)
.Do(dataModel => this.UpdateView(dataModel))
.Subscribe(
dataModel => this.IsBusy = false,
ex =>
{
this.LogService.LogException(ex);
this.ShowError("Something went wrong:", ex);
});
“THANK YOU” → ON COMPLETED

More Related Content

What's hot

JavaOne 2013: Java 8 - The Good Parts
JavaOne 2013: Java 8 - The Good PartsJavaOne 2013: Java 8 - The Good Parts
JavaOne 2013: Java 8 - The Good PartsKonrad Malawski
 
Azure SQL Database - Connectivity Best Practices
Azure SQL Database - Connectivity Best PracticesAzure SQL Database - Connectivity Best Practices
Azure SQL Database - Connectivity Best PracticesJose Manuel Jurado Diaz
 
Akka.NET streams and reactive streams
Akka.NET streams and reactive streamsAkka.NET streams and reactive streams
Akka.NET streams and reactive streamsBartosz Sypytkowski
 
Intro to RxJava/RxAndroid - GDG Munich Android
Intro to RxJava/RxAndroid - GDG Munich AndroidIntro to RxJava/RxAndroid - GDG Munich Android
Intro to RxJava/RxAndroid - GDG Munich AndroidEgor Andreevich
 
Behind modern concurrency primitives
Behind modern concurrency primitivesBehind modern concurrency primitives
Behind modern concurrency primitivesBartosz Sypytkowski
 
Angular and The Case for RxJS
Angular and The Case for RxJSAngular and The Case for RxJS
Angular and The Case for RxJSSandi Barr
 
Async Redux Actions With RxJS - React Rally 2016
Async Redux Actions With RxJS - React Rally 2016Async Redux Actions With RxJS - React Rally 2016
Async Redux Actions With RxJS - React Rally 2016Ben Lesh
 
Reactive programming on Android
Reactive programming on AndroidReactive programming on Android
Reactive programming on AndroidTomáš Kypta
 
Next generation message driven systems with Akka
Next generation message driven systems with AkkaNext generation message driven systems with Akka
Next generation message driven systems with AkkaJohan Andrén
 
Buiilding reactive distributed systems with Akka
Buiilding reactive distributed systems with AkkaBuiilding reactive distributed systems with Akka
Buiilding reactive distributed systems with AkkaJohan Andrén
 
Reactive stream processing using Akka streams
Reactive stream processing using Akka streams Reactive stream processing using Akka streams
Reactive stream processing using Akka streams Johan Andrén
 
RxJava applied [JavaDay Kyiv 2016]
RxJava applied [JavaDay Kyiv 2016]RxJava applied [JavaDay Kyiv 2016]
RxJava applied [JavaDay Kyiv 2016]Igor Lozynskyi
 
Why Redux-Observable?
Why Redux-Observable?Why Redux-Observable?
Why Redux-Observable?Anna Su
 
Next generation message driven systems with Akka
Next generation message driven systems with AkkaNext generation message driven systems with Akka
Next generation message driven systems with AkkaJohan Andrén
 
Next generation actors with Akka
Next generation actors with AkkaNext generation actors with Akka
Next generation actors with AkkaJohan Andrén
 

What's hot (20)

JavaOne 2013: Java 8 - The Good Parts
JavaOne 2013: Java 8 - The Good PartsJavaOne 2013: Java 8 - The Good Parts
JavaOne 2013: Java 8 - The Good Parts
 
Firebase ng2 zurich
Firebase ng2 zurichFirebase ng2 zurich
Firebase ng2 zurich
 
Rxjs swetugg
Rxjs swetuggRxjs swetugg
Rxjs swetugg
 
Azure SQL Database - Connectivity Best Practices
Azure SQL Database - Connectivity Best PracticesAzure SQL Database - Connectivity Best Practices
Azure SQL Database - Connectivity Best Practices
 
Akka.NET streams and reactive streams
Akka.NET streams and reactive streamsAkka.NET streams and reactive streams
Akka.NET streams and reactive streams
 
Intro to RxJava/RxAndroid - GDG Munich Android
Intro to RxJava/RxAndroid - GDG Munich AndroidIntro to RxJava/RxAndroid - GDG Munich Android
Intro to RxJava/RxAndroid - GDG Munich Android
 
Behind modern concurrency primitives
Behind modern concurrency primitivesBehind modern concurrency primitives
Behind modern concurrency primitives
 
Angular and The Case for RxJS
Angular and The Case for RxJSAngular and The Case for RxJS
Angular and The Case for RxJS
 
Async Redux Actions With RxJS - React Rally 2016
Async Redux Actions With RxJS - React Rally 2016Async Redux Actions With RxJS - React Rally 2016
Async Redux Actions With RxJS - React Rally 2016
 
Reactive programming on Android
Reactive programming on AndroidReactive programming on Android
Reactive programming on Android
 
Next generation message driven systems with Akka
Next generation message driven systems with AkkaNext generation message driven systems with Akka
Next generation message driven systems with Akka
 
Oop assignment 02
Oop assignment 02Oop assignment 02
Oop assignment 02
 
Buiilding reactive distributed systems with Akka
Buiilding reactive distributed systems with AkkaBuiilding reactive distributed systems with Akka
Buiilding reactive distributed systems with Akka
 
Reactive stream processing using Akka streams
Reactive stream processing using Akka streams Reactive stream processing using Akka streams
Reactive stream processing using Akka streams
 
AWS Java SDK @ scale
AWS Java SDK @ scaleAWS Java SDK @ scale
AWS Java SDK @ scale
 
RxJava applied [JavaDay Kyiv 2016]
RxJava applied [JavaDay Kyiv 2016]RxJava applied [JavaDay Kyiv 2016]
RxJava applied [JavaDay Kyiv 2016]
 
Why Redux-Observable?
Why Redux-Observable?Why Redux-Observable?
Why Redux-Observable?
 
Rxjs marble-testing
Rxjs marble-testingRxjs marble-testing
Rxjs marble-testing
 
Next generation message driven systems with Akka
Next generation message driven systems with AkkaNext generation message driven systems with Akka
Next generation message driven systems with Akka
 
Next generation actors with Akka
Next generation actors with AkkaNext generation actors with Akka
Next generation actors with Akka
 

Similar to Understanding reactive programming with microsoft reactive extensions

Programming Sideways: Asynchronous Techniques for Android
Programming Sideways: Asynchronous Techniques for AndroidProgramming Sideways: Asynchronous Techniques for Android
Programming Sideways: Asynchronous Techniques for AndroidEmanuele Di Saverio
 
GDG DevFest 2015 - Reactive approach for slowpokes
GDG DevFest 2015 - Reactive approach for slowpokesGDG DevFest 2015 - Reactive approach for slowpokes
GDG DevFest 2015 - Reactive approach for slowpokesSergey Tarasevich
 
Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...
Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...
Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...GeeksLab Odessa
 
Refactoring to Macros with Clojure
Refactoring to Macros with ClojureRefactoring to Macros with Clojure
Refactoring to Macros with ClojureDmitry Buzdin
 
Reactive Programming no Android
Reactive Programming no AndroidReactive Programming no Android
Reactive Programming no AndroidGuilherme Branco
 
Reactive programming on Android
Reactive programming on AndroidReactive programming on Android
Reactive programming on AndroidTomáš Kypta
 
Столпы функционального программирования для адептов ООП, Николай Мозговой
Столпы функционального программирования для адептов ООП, Николай МозговойСтолпы функционального программирования для адептов ООП, Николай Мозговой
Столпы функционального программирования для адептов ООП, Николай МозговойSigma Software
 
4Developers 2015: Programowanie synchroniczne i asynchroniczne - dwa światy k...
4Developers 2015: Programowanie synchroniczne i asynchroniczne - dwa światy k...4Developers 2015: Programowanie synchroniczne i asynchroniczne - dwa światy k...
4Developers 2015: Programowanie synchroniczne i asynchroniczne - dwa światy k...PROIDEA
 
Full-Stack JavaScript with Node.js
Full-Stack JavaScript with Node.jsFull-Stack JavaScript with Node.js
Full-Stack JavaScript with Node.jsMichael Lehmann
 
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 GroupTamir Dresher
 
Building Scalable Stateless Applications with RxJava
Building Scalable Stateless Applications with RxJavaBuilding Scalable Stateless Applications with RxJava
Building Scalable Stateless Applications with RxJavaRick Warren
 
Cycle.js - A functional reactive UI framework
Cycle.js - A functional reactive UI frameworkCycle.js - A functional reactive UI framework
Cycle.js - A functional reactive UI frameworkNikos Kalogridis
 
Cycle.js - Functional reactive UI framework (Nikos Kalogridis)
Cycle.js - Functional reactive UI framework (Nikos Kalogridis)Cycle.js - Functional reactive UI framework (Nikos Kalogridis)
Cycle.js - Functional reactive UI framework (Nikos Kalogridis)GreeceJS
 
UniRx - Reactive Extensions for Unity(EN)
UniRx - Reactive Extensions for Unity(EN)UniRx - Reactive Extensions for Unity(EN)
UniRx - Reactive Extensions for Unity(EN)Yoshifumi Kawai
 
Bulding a reactive game engine with Spring 5 & Couchbase
Bulding a reactive game engine with Spring 5 & CouchbaseBulding a reactive game engine with Spring 5 & Couchbase
Bulding a reactive game engine with Spring 5 & CouchbaseAlex Derkach
 

Similar to Understanding reactive programming with microsoft reactive extensions (20)

Programming Sideways: Asynchronous Techniques for Android
Programming Sideways: Asynchronous Techniques for AndroidProgramming Sideways: Asynchronous Techniques for Android
Programming Sideways: Asynchronous Techniques for Android
 
GDG DevFest 2015 - Reactive approach for slowpokes
GDG DevFest 2015 - Reactive approach for slowpokesGDG DevFest 2015 - Reactive approach for slowpokes
GDG DevFest 2015 - Reactive approach for slowpokes
 
Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...
Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...
Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...
 
Celery with python
Celery with pythonCelery with python
Celery with python
 
Reactive x
Reactive xReactive x
Reactive x
 
Refactoring to Macros with Clojure
Refactoring to Macros with ClojureRefactoring to Macros with Clojure
Refactoring to Macros with Clojure
 
Reactive Programming no Android
Reactive Programming no AndroidReactive Programming no Android
Reactive Programming no Android
 
Reactive programming on Android
Reactive programming on AndroidReactive programming on Android
Reactive programming on Android
 
Lambdas puzzler - Peter Lawrey
Lambdas puzzler - Peter LawreyLambdas puzzler - Peter Lawrey
Lambdas puzzler - Peter Lawrey
 
Столпы функционального программирования для адептов ООП, Николай Мозговой
Столпы функционального программирования для адептов ООП, Николай МозговойСтолпы функционального программирования для адептов ООП, Николай Мозговой
Столпы функционального программирования для адептов ООП, Николай Мозговой
 
4Developers 2015: Programowanie synchroniczne i asynchroniczne - dwa światy k...
4Developers 2015: Programowanie synchroniczne i asynchroniczne - dwa światy k...4Developers 2015: Programowanie synchroniczne i asynchroniczne - dwa światy k...
4Developers 2015: Programowanie synchroniczne i asynchroniczne - dwa światy k...
 
Full-Stack JavaScript with Node.js
Full-Stack JavaScript with Node.jsFull-Stack JavaScript with Node.js
Full-Stack JavaScript with Node.js
 
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
 
Building Scalable Stateless Applications with RxJava
Building Scalable Stateless Applications with RxJavaBuilding Scalable Stateless Applications with RxJava
Building Scalable Stateless Applications with RxJava
 
Cycle.js - A functional reactive UI framework
Cycle.js - A functional reactive UI frameworkCycle.js - A functional reactive UI framework
Cycle.js - A functional reactive UI framework
 
Cycle.js - Functional reactive UI framework (Nikos Kalogridis)
Cycle.js - Functional reactive UI framework (Nikos Kalogridis)Cycle.js - Functional reactive UI framework (Nikos Kalogridis)
Cycle.js - Functional reactive UI framework (Nikos Kalogridis)
 
UniRx - Reactive Extensions for Unity(EN)
UniRx - Reactive Extensions for Unity(EN)UniRx - Reactive Extensions for Unity(EN)
UniRx - Reactive Extensions for Unity(EN)
 
Coding in Style
Coding in StyleCoding in Style
Coding in Style
 
Bulding a reactive game engine with Spring 5 & Couchbase
Bulding a reactive game engine with Spring 5 & CouchbaseBulding a reactive game engine with Spring 5 & Couchbase
Bulding a reactive game engine with Spring 5 & Couchbase
 
Rx workshop
Rx workshopRx workshop
Rx workshop
 

Recently uploaded

Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Hr365.us smith
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsAhmed Mohamed
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEOrtus Solutions, Corp
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...gurkirankumar98700
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio, Inc.
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)OPEN KNOWLEDGE GmbH
 
英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作qr0udbr0
 
Unveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesUnveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesŁukasz Chruściel
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWave PLM
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based projectAnoyGreter
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEEVICTOR MAESTRE RAMIREZ
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesPhilip Schwarz
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfAlina Yurenko
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxTier1 app
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityNeo4j
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...stazi3110
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...Christina Lin
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Velvetech LLC
 
The Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfThe Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfPower Karaoke
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software DevelopersVinodh Ram
 

Recently uploaded (20)

Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML Diagrams
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)
 
英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作
 
Unveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesUnveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New Features
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need It
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based project
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEE
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a series
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered Sustainability
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...
 
The Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfThe Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdf
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software Developers
 

Understanding reactive programming with microsoft reactive extensions

  • 1. Understanding reactive programming with Microsoft Reactive Extensions Oleksandr Zhevzhyk, 2017
  • 2. WHY REACTIVE? ● Have a curious interface (-= and +=) ● Are difficult to compose ● Don't offer the ability to be easily queried over time ● Provide almost no help for concurrency or multithreaded applications ● No blocking while waiting for a result ● The result is pushed to you when it is ready ● Developers need tools to react to pushed data EVENTS ● Have nothing to do with events ● Handling exceptions, cancellation and synchronization is difficult ● Much better that events, but still difficult to compose TASKS REACTIVE IS THE NEW BLACK REACTIVE PROGRAMMING IS PROGRAMMING WITH ASYNCHRONOUS DATA STREAMS
  • 3. RX: HELPFUL RESOURCES GitHub https://github.com/Reactive-Extensions NuGet System.Reactive (main library) > Install-Package System.Reactive MSDN https://msdn.microsoft.com/library/hh242985.aspx “Intro to Rx” by Lee Campbell http://introtorx.com Online / Kindle / EPUBStack Overflow system.reactive tag http://stackoverflow.com/questions/tagged/system.reactive
  • 4. RX: IMPLEMENTATIONS Rx.NET - Reactive Extensions for .NET RxJS - Reactive Extensions for JavaScript RxJS-ExtJS - Ext JS Bindings for RxJS rx.angular.js - AngularJS Bindings for RxJS RxJS-DOM - HTML DOM Bindings for RxJS RxCpp - Reactive Extensions for C++ Rx.ObjC - Reactive Extensions for Objective C RxPy - Reactive Extensions for Python
  • 5. WHAT IS RX? Rx is a library for composing asynchronous and event-based programs using observable sequences and LINQ-style query operators. With Rx you: - represent asynchronous data streams with Observables - query asynchronous data streams using LINQ operators - control the concurrency in the asynchronous data streams using Schedulers. Rx = Observables + LINQ + Schedulers
  • 6. OnNext* (OnCompleted | OnError)? OBSERVABLE: GRAMMAR
  • 7. OBSERVABLE: CORE INTERFACES IObservable<T> .Subscribe ( Action<T> onNext, Action<Exception> onError, Action onCompleted) IObserver<T> .OnNext (T value) .OnCompleted () .OnError(Exception ex) IObservable<string> namesObservable = ...; namesObservable.Subscribe( name => this.List.Add(name), ex => this.LogService.LogException(ex); () => this.RaiseNamesReady(EventArgs.Empty));
  • 9. OBSERVABLE: FACTORIES#1 Observable.Never<int>(): ∅ Observable.Empty<bool>(): OnCompleted Observable.Generate(1, x => x < 6, x => x + 2, x => x*x): 1 → 9 → 25 → OnCompleted Observable.Throw<float>(): OnError Observable.Return(“abc”): “abc” → OnCompleted
  • 10. OBSERVABLE: FACTORIES#2 ConsoleCancelEventArgs → ConsoleCancelEventArgs → … (∞) Observable.FromEventPattern<ConsoleCancelEventHandler, ConsoleCancelEventArgs>( h => Console.CancelKeyPress += h, h => Console.CancelKeyPress -= h); var fileStream = new FileStream(file, FileMode.Open); var observableFactory = Observable.FromAsyncPattern<byte[], int, int, int>( fileStream.BeginRead, fileStream.EndRead); var bytes = new byte[fileStream.Length]; observableFactory(bytes, 0, fileStream.Length) .Subscribe(actualRead => { /*process bytes*/ }); actualRead → OnCompleted FROM APM FROM EVENT
  • 11. OBSERVABLE: FACTORIES#3 Observable.FromAsync(() => Task.Factory.StartNew(() => { Thread.Sleep(5000); return "404"; })); FROM TASK “404” → OnCompleted Observable.Using( () => new FileStream(@"C:movie.mkv", FileMode.Open), fs => this.ReadFileObservable(fs)); FROM IDISPOSABLE
  • 12. OBSERVABLE: FACTORIES#4 Bob → Bill → Alice → OnCompleted var names = Observable.Create<string>( observer => { observer.OnNext("Bob"); observer.OnNext("Bill"); observer.OnNext("Alice"); observer.OnCompleted(); return Disposable.Empty; }); Not asynchronous Not cancellable var observable = Observable.Create<int>(observer => { var cd = new CancellationDisposable(); var pause = TimeSpan.FromSeconds(3); int counter = 0; Action action = () => { if (!cd.Token.IsCancellationRequested) { observer.OnNext(++counter); if (counter == 5) observer.OnCompleted(); else scheduler.Schedule(pause, action); } }; scheduler.Schedule(action); return cd; }); 1 → 2 → 3 → 4 → 5 → OnCompleted
  • 13. OBSERVABLE: CANCELLATION Subscribe() returns an IDisposable. Keep it. public void Initialize() { this._updateUriDisposable = Observable .FromEventPattern<EventHandler<UriChangedEventArgs>, UriChangedEventArgs>( h => this.Options.UriChanged += h, h => this.Options.UriChanged -= h) .SelectMany(args => this.RestRequestService.Get(args.EventArgs.Uri, Scheduler.ThreadPool)) .ObserveOn(this.Dispatcher) .Subscribe( response => this.WebView.Update(response), ex => this.HandleError(ex)); } public void Close() { this._updateUriDisposable.Dispose(); } Call Dispose on it to stop the Observable.
  • 14. OBSERVABLE: CLEANUP RX IS TIDY WHEN Observable has finished with OnCompleted or OnError Observable was manually stopped by Disposable var changedDisposable = Observable.FromEventPattern(model, nameof(model.Changed)) .Finally(() => Console.WriteLine("Disposed!")) .Subscribe(); //... changedDisposable.Dispose(); Use Finally() when you want to track disposal of the data stream
  • 15. LINQ: OVERVIEW - projection - filtering - aggregation - composing - time-based operations You could think: RX is LINQ to events
  • 16. LINQ: FILTERING Where Take / TakeWhile Skip / SkipWhile FirstAsync LastAsync Observable .FromEventPattern( h => textBox.KeyPress += h, h => textBox.KeyPress -= h) .Where(_ => _.EventArgs.KeyCode == Keys.Enter) .Skip(10) .Take(3) .FirstAsync() .Subscribe(_ => { }); EventPattern → OnCompleted
  • 17. LINQ: PROJECTION Select Observable.Return(100) .Select(num => num.ToString()) .Subscribe(str => Console.Write(str)); IObservable<T1> → IObservable<T2> Select + Switch SelectMany observable123.SelectMany(num => observableABCD) observable123.Select(n => observableABCD).Switch() IObservable<T1> → IObservable<IObservable<T2>>
  • 18. LINQ: PROJECTION#SELECT MANY observable123 .SelectMany(num => observableABCD) .Subscribe(letter => Console.WriteLine(letter));
  • 19. LINQ: PROJECTION#SELECT+SWITCH observable123 .Select(num => observableABCD) .Switch() .Subscribe(letter => Console.WriteLine(letter));
  • 20. LINQ: AGGREGATION ToArray GroupBy Aggregate All Any observable123.ToArray().Subscribe(array => { }); [1, 2, 3] → OnCompleted All aggregation functions produce an observable with an aggregated result! ... observable123 .SelectMany(num => observableABCD) .GroupBy(l => l) .Subscribe(grouped => grouped .Aggregate("", (l, res) => res + l) .Subscribe(aggr => { })); “AAA” → “BBB” → “CCC” → “DDD” → OnCompleted
  • 21. LINQ: COMPOSING Fork/Join Observable .When(observableABCD .And(observable123) .Then((l, n) => new {Letter = l, Number = n})) .Subscribe(pair => { }); {“A”, 1} → {“B”,2} → {“C”,3} → OnCompleted CombineLatest Observable .CombineLatest( observable123, observableABCD, (l, n) => new { Letter = l, Number = n }) .Subscribe(); {“C”, 1} → {“C”,2} → {“D”,2} → {“D”,3} → OnCompleted Merge observable123.Merge(observable789).Subscribe(n => { }); 1 → 7 → 2 → 3 → 8 → 9 → OnCompleted Concat 1 → 2 → 3 → 7 → 8 → 9 → OnCompleted observable123.Concat(observable789).Subscribe(n => { }); SkipUntil / TakeUntil observable123 .SkipUntil(observable789) .Subscribe(n => { }); 1 → 2 → OnCompleted
  • 22. RX: SCHEDULERS By default: single threaded. IScheduler Scheduler.CurrentThread Scheduler.ThreadPool DispatcherScheduler TestScheduler - Some Rx methods accept IScheduler Observable .Return(“data”, Scheduler.ThreadPool) .Subscribe(_ => {/*worker thread*/}); - ObserveOn method observable123 .ObserveOn(Scheduler.ThreadPool) .Select(n => n.ToString()) .ObserveOn(this.Dispatcher) .Subscribe(s => { })
  • 23. EXCEPTION HANDLING Everything what happens in Observable stays in Observable. Besides onNext/onCompleted in Subscribe! observable123 .SelectMany(n => Observable.When(observableABCD .And(observableXY) .Then((l1, l2) => l1 + l2)) .Select(word => ProccessWord(word))) .Subscribe(_ => { }, ex => { }); Exception! Exception! Exception! _restService.Get(uri, Scheduler.ThreadPool) .Catch<RestException>( ex => Observable.Return("[]")) .Subscribe(data => { }); Swallowing exceptions with Catch method
  • 24. FIELD EXAMPLE Refresh event UriChanged event Closed event 3 async web requests public IObservable<JArray> DataObservable(Uri uri, string resource) { return RestRequestService .Get(Scheduler.ThreadPool, Options.Uri, resource) .Catch<RestException>(ex => { this.LogService.LogException(ex); return "[]"; }) .Select(json => Json.Parse(json)); } uriChanged.Merge(refreshRequested) .Do(_ => this.IsBusy = true) .Select(opt => Observable .When(this.DataObservable(opt.Uri, "cars") .And(this.DataObservable(opt.Uri, "trams") .And(this.DataObservable(opt.Uri, "planes")) .Then((cars, trams, planes) => this.CreateDataModel(cars, trams, planes))))) .Switch() .TakeUntil(closeRequested) .ObserveOn(this.Dispatcher) .Do(dataModel => this.UpdateView(dataModel)) .Subscribe( dataModel => this.IsBusy = false, ex => { this.LogService.LogException(ex); this.ShowError("Something went wrong:", ex); });
  • 25. “THANK YOU” → ON COMPLETED