SlideShare a Scribd company logo
1 of 35
Download to read offline
Don’t Cross the Streams…

Matthew Podwysocki
@mattpodwysocki
Callback Hell…
app.get('/index', function (req, res, next) {
    User.get(req.params.userId, function (err, user) {
        if (err) next(err);
        db.find({user: user.name}, function (err, cursor) {
            if (err) next(err);
            cursor.toArray(function (err, items) {
                if (err) next(err);
                res.send(items);
            });
        });
    });
});
                      …and the Pyramid of Doom
The promise of a better future…


tweetsAsync()
    .then(function (a) { return usersAsync(a); })
    .then(function (b) { return locationAsync(b); })
    .done(function (c) { render(); });
What about events?
• What about composition?
• How do I clean up handlers?
• How do I merge streams?
• Or filter?
• Or aggregate?
• Without having a lot of state hanging around?
• The list goes on and on…
In other words…




                  We cross the streams!
What is it?
• RxJS is…
  • a set of types representing asynchronous data streams
  • a set of operators over asynchronous data streams
  • a set of types to parameterize concurrency


RxJS = Observables + LINQ + Schedulers
Not another flow control library…

                             Why bother?
var mousedrag = mousedown.selectMany(function (md) {

      // calculate offsets when mouse down
      var startX = md.offsetX,
          startY = md.offsetY;

      // calculate diffs until mouse up
      return mousemove.select(function (mm) {
          return {
              left: mm.clientX - startX,
              top: mm.clientY - startY
          };
      }).takeUntil(mouseup);
});
                            Rich Composite Events…
var words = Rx.Observable.fromEvent(input, "keyup")
            .select(function(x) { return input.value; })
            .throttle(500)
            .distinctUntilChanged()
            .select(function(term) { return search(term); })
            .switchLatest();

words.subscribe(function (data) {
    // Bind data to the UI
});



                                         Control Flow…
stockTicks
  .groupBy(function (tick) { return tick.symbol; })
  .selectMany(
    function (g) { return g.bufferWithCount(2, 1); },
    function (g, b) { return { key: g.key, b: b }; })
  .select(function (c) {
    return { diff: (c.b[1] – c.b[0]) / c.b[0], symbol: c.key };
  })
  .where(function (c) { return c.diff > 0.1; })
  .select(function (c) {
    return { company: c.symbol, increase: c.diff };
  });
                     Complex Event Processing…
var sequence = '38,38,40,40,37,39,37,39,66,65';

var keyups = Rx.Observable.fromEvent(document, 'keyup')
     .select(function (x) { return x.keyCode; })
     .bufferWithCount(10, 10)
     .subscribe(function (x) {
           var matches = x.join() === sequence;
           if (matches) console.log('Konami');
     });
What is it?
• RxJS is…
  • a set of types representing asynchronous data streams
  • a set of operators over asynchronous data streams
  • a set of types to parameterize concurrency


RxJS = Observables + LINQ + Schedulers
The Essentials…
Observer = {
  onNext :
    function (data) { … },        Observable = {
  onError :                         subscribe :
    function (error) { … },           function (observer) { … }
  onCompleted :                   };
    function ()      { … }
};
                                           Observable

                      Subscribe


   Observer
The Grammar Police…

•   Zero or more values
                       *          ( OnError       | OnCompleted ) ?
•   E.g. events are ∞ sequences



                   0                   1                     2


                       0               1
                                                     • It’s a sequence
                   0        1          2             • No concurrent
                                                       callbacks
                                                     • One time termination
                            0      1          2
First Class Events…
What?
• RxJS is…
  • a set of types representing asynchronous data streams
  • a set of operators over asynchronous data streams
  • a set of types to parameterize concurrency


RxJS = Observables + LINQ + Schedulers
If you know ES5 Array “extras”…
Array              Observable
• Querying         • Querying
   •    concat        •   concat
   •    every         •   all
   •    filter        •   where
   •    map           •   select
   •    reduce        •   aggregate
   •    some          •   any

• Subscribing      • Subscribing
   • forEach          • subscribe


                             … then you know RxJS
Querying Asynchronous Streams

• Observables are data streams
   • Hence we can query them like we do with Arrays!



     function
return
Querying Asynchronous Streams

• Observables are asynchronous
  • Hence, they have a notion of time
Limited only by imagination…
aggregate                   generateWithRelativeTime   selectMany
all                         groupBy                    sequenceEqual
amb                                                    skip
                            groupByUntil               skipLast
any                         groupJoin                  skipUntil
asObservable                                           skipWhile
average                     ignoreElements
                            interval                   start
buffer                                                 startWith
                            join                       subscribe
bufferWithCount
bufferWithTime              materialize                subscribeOn
                            max                        sum
bufferWithTimeOrCount                                  switchLatest
catchException              maxBy                      take
combineLatest               merge                      takeLast
concat                      mergeObservable            takeLastBuffer
concatObservable            min                        takeUntil
contains                    minBy                      takeWhile
count                       multicast                  then
create                                                 throttle
                            never                      throwException
createWithDisposable
defaultIfEmpty              observeOn                  timeInterval
                            onErrorResumeNext          timeout
defer                                                  timer
delay                       publish                    using
dematerialize               publishLast                when
distinct                    range                      where
disinctUntilChanged         refCount                   window
doAction                    repeat                     windowWithCount
elementAt                                              windowWithAbsoluteTime
elementAtOrDefault          replay                     windowWithRelativeTime
empty                       retry                      zip
generate                    returnValue
generateWithAbsoluteTime    sample
                            scan
                            select
Creation operators
                   create*
                   empty
                 fromArray
                 generate*
                    never
                    range
                   repeat
                returnValue
Standard operators
                     distinct
             distinctUntilChanged
                    groupBy
                      select
                   selectMany
                      skip*
                      take*
                      where
Aggregation operators
                aggregate
                    all
                   any
                 contains
                  count
                   min
                   max
                   scan
Error handling operators

                catchException
                  finallyAction
              onErrorResumeNext
                      retry
                throwException
                      using
Complex Event operators


                 buffer*
                groupJoin
                   join
                window*
                 sample
Orchestration operators
               combineLatest
                   concat
                  forkJoin
                   merge
                 skipUntil
                switchLatest
                 takeUntil
                     zip
Time based operators

                    delay
                  interval
                  throttle
                  timeout
               timeInterval
                    timer
                timeStamp
What?
• RxJS is…
  • a set of types representing asynchronous data streams
  • a set of operators over asynchronous data streams
  • a set of types to parameterize concurrency


RxJS = Observables + LINQ + Schedulers
The Role of Schedulers…
                                                          Many
                                                     implementations
• Key questions:
                                Cancellation
  • How to run timers?
  • Where to produce events?                   d = scheduler.schedule(
                                                 function () {
  • Need to synchronize with the UI?
                                                   // Asynchronously
                                                   // running work
• Providing one answer:                          },
  • Schedulers introduce concurrency             1000);
  • Operators are parameterized by schedulers              Optional time
  • Provides test benefits as well
var scheduler = new TestScheduler();

var input = scheduler.createColdObservable(
    onNext(300, "Cascadia"),
    onNext(400, "JS"),
    onCompleted(500));

var results = scheduler.startWithCreate(function () {
    input.select(function (x) { return x.length; })
});

results.messages.assertEqual(
    onNext(300, 8),
    onNext(400, 2),                    Testability is King!
    onCompleted(500));
Start using it now
Node.js
> npm install rx

NuGet
> Install-Package RxJS

Open Source
http://rx.codeplex.com/
What’s Next?
• Ongoing work
  • Documentation
  • Tutorials


• Where’s the vision?
  • Scaling
  • Distributed
  • Merge with Node.js Streams
Cross the Streams…

Matthew Podwysocki
@mattpodwysocki
matthewp@microsoft.com
Credits
• Cross the Streams -
  https://oshea12566.wordpress.com/2012/02/20/jeep-meeting-and-
  trail-ride/
• NES Controller - http://en.wikipedia.org/wiki/File:NES-controller.jpg

More Related Content

What's hot

RxJS 5 in Depth
RxJS 5 in DepthRxJS 5 in Depth
RxJS 5 in DepthC4Media
 
Reactive Programming Patterns with RxSwift
Reactive Programming Patterns with RxSwiftReactive Programming Patterns with RxSwift
Reactive Programming Patterns with RxSwiftFlorent Pillet
 
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
 
Angular and The Case for RxJS
Angular and The Case for RxJSAngular and The Case for RxJS
Angular and The Case for RxJSSandi Barr
 
RxJS101 - What you need to know to get started with RxJS tomorrow
RxJS101 - What you need to know to get started with RxJS tomorrowRxJS101 - What you need to know to get started with RxJS tomorrow
RxJS101 - What you need to know to get started with RxJS tomorrowViliam Elischer
 
Think Async: Asynchronous Patterns in NodeJS
Think Async: Asynchronous Patterns in NodeJSThink Async: Asynchronous Patterns in NodeJS
Think Async: Asynchronous Patterns in NodeJSAdam L Barrett
 
Introduction to rx java for android
Introduction to rx java for androidIntroduction to rx java for android
Introduction to rx java for androidEsa Firman
 
Introduction to RxJS
Introduction to RxJSIntroduction to RxJS
Introduction to RxJSBrainhub
 
Reactive, component 그리고 angular2
Reactive, component 그리고  angular2Reactive, component 그리고  angular2
Reactive, component 그리고 angular2Jeado Ko
 
rx.js make async programming simpler
rx.js make async programming simplerrx.js make async programming simpler
rx.js make async programming simplerAlexander Mostovenko
 
Swift & ReactiveX – Asynchronous Event-Based Funsies with RxSwift
Swift & ReactiveX – Asynchronous Event-Based Funsies with RxSwiftSwift & ReactiveX – Asynchronous Event-Based Funsies with RxSwift
Swift & ReactiveX – Asynchronous Event-Based Funsies with RxSwiftAaron Douglas
 
Functional Reactive Programming (FRP): Working with RxJS
Functional Reactive Programming (FRP): Working with RxJSFunctional Reactive Programming (FRP): Working with RxJS
Functional Reactive Programming (FRP): Working with RxJSOswald Campesato
 
My Gentle Introduction to RxJS
My Gentle Introduction to RxJSMy Gentle Introduction to RxJS
My Gentle Introduction to RxJSMattia Occhiuto
 
Reactive Programming with RxSwift
Reactive Programming with RxSwiftReactive Programming with RxSwift
Reactive Programming with RxSwiftScott Gardner
 
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
 

What's hot (20)

Angular2 rxjs
Angular2 rxjsAngular2 rxjs
Angular2 rxjs
 
RxJS 5 in Depth
RxJS 5 in DepthRxJS 5 in Depth
RxJS 5 in Depth
 
Rxjs ppt
Rxjs pptRxjs ppt
Rxjs ppt
 
Reactive Programming Patterns with RxSwift
Reactive Programming Patterns with RxSwiftReactive Programming Patterns with RxSwift
Reactive Programming Patterns with RxSwift
 
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
 
Angular and The Case for RxJS
Angular and The Case for RxJSAngular and The Case for RxJS
Angular and The Case for RxJS
 
RxJS101 - What you need to know to get started with RxJS tomorrow
RxJS101 - What you need to know to get started with RxJS tomorrowRxJS101 - What you need to know to get started with RxJS tomorrow
RxJS101 - What you need to know to get started with RxJS tomorrow
 
Think Async: Asynchronous Patterns in NodeJS
Think Async: Asynchronous Patterns in NodeJSThink Async: Asynchronous Patterns in NodeJS
Think Async: Asynchronous Patterns in NodeJS
 
Introduction to rx java for android
Introduction to rx java for androidIntroduction to rx java for android
Introduction to rx java for android
 
Introduction to RxJS
Introduction to RxJSIntroduction to RxJS
Introduction to RxJS
 
Reactive, component 그리고 angular2
Reactive, component 그리고  angular2Reactive, component 그리고  angular2
Reactive, component 그리고 angular2
 
rx.js make async programming simpler
rx.js make async programming simplerrx.js make async programming simpler
rx.js make async programming simpler
 
Oop assignment 02
Oop assignment 02Oop assignment 02
Oop assignment 02
 
Swift & ReactiveX – Asynchronous Event-Based Funsies with RxSwift
Swift & ReactiveX – Asynchronous Event-Based Funsies with RxSwiftSwift & ReactiveX – Asynchronous Event-Based Funsies with RxSwift
Swift & ReactiveX – Asynchronous Event-Based Funsies with RxSwift
 
Functional Reactive Programming (FRP): Working with RxJS
Functional Reactive Programming (FRP): Working with RxJSFunctional Reactive Programming (FRP): Working with RxJS
Functional Reactive Programming (FRP): Working with RxJS
 
My Gentle Introduction to RxJS
My Gentle Introduction to RxJSMy Gentle Introduction to RxJS
My Gentle Introduction to RxJS
 
Reactive Programming with RxSwift
Reactive Programming with RxSwiftReactive Programming with RxSwift
Reactive Programming with RxSwift
 
Rxjs ngvikings
Rxjs ngvikingsRxjs ngvikings
Rxjs ngvikings
 
Rxjs kyivjs 2015
Rxjs kyivjs 2015Rxjs kyivjs 2015
Rxjs kyivjs 2015
 
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
 

Viewers also liked

NDC14 - Rx와 Functional Reactive Programming으로 고성능 서버 만들기
NDC14 - Rx와 Functional Reactive Programming으로 고성능 서버 만들기NDC14 - Rx와 Functional Reactive Programming으로 고성능 서버 만들기
NDC14 - Rx와 Functional Reactive Programming으로 고성능 서버 만들기Jong Wook Kim
 
Functional Reactive Programming With RxSwift
Functional Reactive Programming With RxSwiftFunctional Reactive Programming With RxSwift
Functional Reactive Programming With RxSwift선협 이
 
[1B4]안드로이드 동시성_프로그래밍
[1B4]안드로이드 동시성_프로그래밍[1B4]안드로이드 동시성_프로그래밍
[1B4]안드로이드 동시성_프로그래밍NAVER D2
 
RxJS and Reactive Programming - Modern Web UI - May 2015
RxJS and Reactive Programming - Modern Web UI - May 2015RxJS and Reactive Programming - Modern Web UI - May 2015
RxJS and Reactive Programming - Modern Web UI - May 2015Ben Lesh
 
혁신적인 웹컴포넌트 라이브러리 - Polymer
혁신적인 웹컴포넌트 라이브러리 - Polymer혁신적인 웹컴포넌트 라이브러리 - Polymer
혁신적인 웹컴포넌트 라이브러리 - PolymerJae Sung Park
 
FalsyValues. Dmitry Soshnikov - ECMAScript 6
FalsyValues. Dmitry Soshnikov - ECMAScript 6FalsyValues. Dmitry Soshnikov - ECMAScript 6
FalsyValues. Dmitry Soshnikov - ECMAScript 6Dmitry Soshnikov
 
Module, AMD, RequireJS
Module, AMD, RequireJSModule, AMD, RequireJS
Module, AMD, RequireJS偉格 高
 
System webpack-jspm
System webpack-jspmSystem webpack-jspm
System webpack-jspmJesse Warden
 
React in Native Apps - Meetup React - 20150409
React in Native Apps - Meetup React - 20150409React in Native Apps - Meetup React - 20150409
React in Native Apps - Meetup React - 20150409Minko3D
 
맛만 보자 액터 모델이란
맛만 보자 액터 모델이란 맛만 보자 액터 모델이란
맛만 보자 액터 모델이란 jbugkorea
 
React JS and why it's awesome
React JS and why it's awesomeReact JS and why it's awesome
React JS and why it's awesomeAndrew Hull
 
LetSwift RxSwift 시작하기
LetSwift RxSwift 시작하기LetSwift RxSwift 시작하기
LetSwift RxSwift 시작하기Wanbok Choi
 

Viewers also liked (13)

NDC14 - Rx와 Functional Reactive Programming으로 고성능 서버 만들기
NDC14 - Rx와 Functional Reactive Programming으로 고성능 서버 만들기NDC14 - Rx와 Functional Reactive Programming으로 고성능 서버 만들기
NDC14 - Rx와 Functional Reactive Programming으로 고성능 서버 만들기
 
Functional Reactive Programming With RxSwift
Functional Reactive Programming With RxSwiftFunctional Reactive Programming With RxSwift
Functional Reactive Programming With RxSwift
 
[1B4]안드로이드 동시성_프로그래밍
[1B4]안드로이드 동시성_프로그래밍[1B4]안드로이드 동시성_프로그래밍
[1B4]안드로이드 동시성_프로그래밍
 
RxJS and Reactive Programming - Modern Web UI - May 2015
RxJS and Reactive Programming - Modern Web UI - May 2015RxJS and Reactive Programming - Modern Web UI - May 2015
RxJS and Reactive Programming - Modern Web UI - May 2015
 
혁신적인 웹컴포넌트 라이브러리 - Polymer
혁신적인 웹컴포넌트 라이브러리 - Polymer혁신적인 웹컴포넌트 라이브러리 - Polymer
혁신적인 웹컴포넌트 라이브러리 - Polymer
 
FalsyValues. Dmitry Soshnikov - ECMAScript 6
FalsyValues. Dmitry Soshnikov - ECMAScript 6FalsyValues. Dmitry Soshnikov - ECMAScript 6
FalsyValues. Dmitry Soshnikov - ECMAScript 6
 
Module, AMD, RequireJS
Module, AMD, RequireJSModule, AMD, RequireJS
Module, AMD, RequireJS
 
System webpack-jspm
System webpack-jspmSystem webpack-jspm
System webpack-jspm
 
Angular2 ecosystem
Angular2 ecosystemAngular2 ecosystem
Angular2 ecosystem
 
React in Native Apps - Meetup React - 20150409
React in Native Apps - Meetup React - 20150409React in Native Apps - Meetup React - 20150409
React in Native Apps - Meetup React - 20150409
 
맛만 보자 액터 모델이란
맛만 보자 액터 모델이란 맛만 보자 액터 모델이란
맛만 보자 액터 모델이란
 
React JS and why it's awesome
React JS and why it's awesomeReact JS and why it's awesome
React JS and why it's awesome
 
LetSwift RxSwift 시작하기
LetSwift RxSwift 시작하기LetSwift RxSwift 시작하기
LetSwift RxSwift 시작하기
 

Similar to Cascadia.js: Don't Cross the Streams

WebCamp:Front-end Developers Day. Александр Мостовенко "Rx.js - делаем асинхр...
WebCamp:Front-end Developers Day. Александр Мостовенко "Rx.js - делаем асинхр...WebCamp:Front-end Developers Day. Александр Мостовенко "Rx.js - делаем асинхр...
WebCamp:Front-end Developers Day. Александр Мостовенко "Rx.js - делаем асинхр...GeeksLab Odessa
 
响应式编程及框架
响应式编程及框架响应式编程及框架
响应式编程及框架jeffz
 
The Evolution of Async-Programming (SD 2.0, JavaScript)
The Evolution of Async-Programming (SD 2.0, JavaScript)The Evolution of Async-Programming (SD 2.0, JavaScript)
The Evolution of Async-Programming (SD 2.0, JavaScript)jeffz
 
Java basic tutorial by sanjeevini india
Java basic tutorial by sanjeevini indiaJava basic tutorial by sanjeevini india
Java basic tutorial by sanjeevini indiasanjeeviniindia1186
 
Java basic tutorial by sanjeevini india
Java basic tutorial by sanjeevini indiaJava basic tutorial by sanjeevini india
Java basic tutorial by sanjeevini indiaSanjeev Tripathi
 
Asynchronous programming done right - Node.js
Asynchronous programming done right - Node.jsAsynchronous programming done right - Node.js
Asynchronous programming done right - Node.jsPiotr Pelczar
 
Artimon - Apache Flume (incubating) NYC Meetup 20111108
Artimon - Apache Flume (incubating) NYC Meetup 20111108Artimon - Apache Flume (incubating) NYC Meetup 20111108
Artimon - Apache Flume (incubating) NYC Meetup 20111108Mathias Herberts
 
Async and parallel patterns and application design - TechDays2013 NL
Async and parallel patterns and application design - TechDays2013 NLAsync and parallel patterns and application design - TechDays2013 NL
Async and parallel patterns and application design - TechDays2013 NLArie Leeuwesteijn
 
Akka london scala_user_group
Akka london scala_user_groupAkka london scala_user_group
Akka london scala_user_groupSkills Matter
 
Aplicações assíncronas no Android com
Coroutines & Jetpack
Aplicações assíncronas no Android com
Coroutines & JetpackAplicações assíncronas no Android com
Coroutines & Jetpack
Aplicações assíncronas no Android com
Coroutines & JetpackNelson Glauber Leal
 
Reacting with ReactiveUI
Reacting with ReactiveUIReacting with ReactiveUI
Reacting with ReactiveUIkiahiska
 
Node.js Event Loop & EventEmitter
Node.js Event Loop & EventEmitterNode.js Event Loop & EventEmitter
Node.js Event Loop & EventEmitterSimen Li
 
Synapseindia reviews.odp.
Synapseindia reviews.odp.Synapseindia reviews.odp.
Synapseindia reviews.odp.Tarunsingh198
 
Kotlin coroutines and spring framework
Kotlin coroutines and spring frameworkKotlin coroutines and spring framework
Kotlin coroutines and spring frameworkSunghyouk Bae
 
Java tut1 Coderdojo Cahersiveen
Java tut1 Coderdojo CahersiveenJava tut1 Coderdojo Cahersiveen
Java tut1 Coderdojo CahersiveenGraham Royce
 

Similar to Cascadia.js: Don't Cross the Streams (20)

WebCamp:Front-end Developers Day. Александр Мостовенко "Rx.js - делаем асинхр...
WebCamp:Front-end Developers Day. Александр Мостовенко "Rx.js - делаем асинхр...WebCamp:Front-end Developers Day. Александр Мостовенко "Rx.js - делаем асинхр...
WebCamp:Front-end Developers Day. Александр Мостовенко "Rx.js - делаем асинхр...
 
响应式编程及框架
响应式编程及框架响应式编程及框架
响应式编程及框架
 
Rx workshop
Rx workshopRx workshop
Rx workshop
 
The Evolution of Async-Programming (SD 2.0, JavaScript)
The Evolution of Async-Programming (SD 2.0, JavaScript)The Evolution of Async-Programming (SD 2.0, JavaScript)
The Evolution of Async-Programming (SD 2.0, JavaScript)
 
Java basic tutorial by sanjeevini india
Java basic tutorial by sanjeevini indiaJava basic tutorial by sanjeevini india
Java basic tutorial by sanjeevini india
 
Java basic tutorial by sanjeevini india
Java basic tutorial by sanjeevini indiaJava basic tutorial by sanjeevini india
Java basic tutorial by sanjeevini india
 
Asynchronous programming done right - Node.js
Asynchronous programming done right - Node.jsAsynchronous programming done right - Node.js
Asynchronous programming done right - Node.js
 
Reactive x
Reactive xReactive x
Reactive x
 
Artimon - Apache Flume (incubating) NYC Meetup 20111108
Artimon - Apache Flume (incubating) NYC Meetup 20111108Artimon - Apache Flume (incubating) NYC Meetup 20111108
Artimon - Apache Flume (incubating) NYC Meetup 20111108
 
Async and parallel patterns and application design - TechDays2013 NL
Async and parallel patterns and application design - TechDays2013 NLAsync and parallel patterns and application design - TechDays2013 NL
Async and parallel patterns and application design - TechDays2013 NL
 
Java Tutorial
Java Tutorial Java Tutorial
Java Tutorial
 
Rxjs marble-testing
Rxjs marble-testingRxjs marble-testing
Rxjs marble-testing
 
Akka london scala_user_group
Akka london scala_user_groupAkka london scala_user_group
Akka london scala_user_group
 
Aplicações assíncronas no Android com
Coroutines & Jetpack
Aplicações assíncronas no Android com
Coroutines & JetpackAplicações assíncronas no Android com
Coroutines & Jetpack
Aplicações assíncronas no Android com
Coroutines & Jetpack
 
Reacting with ReactiveUI
Reacting with ReactiveUIReacting with ReactiveUI
Reacting with ReactiveUI
 
Node.js Event Loop & EventEmitter
Node.js Event Loop & EventEmitterNode.js Event Loop & EventEmitter
Node.js Event Loop & EventEmitter
 
Synapseindia reviews.odp.
Synapseindia reviews.odp.Synapseindia reviews.odp.
Synapseindia reviews.odp.
 
Kotlin coroutines and spring framework
Kotlin coroutines and spring frameworkKotlin coroutines and spring framework
Kotlin coroutines and spring framework
 
Java tut1
Java tut1Java tut1
Java tut1
 
Java tut1 Coderdojo Cahersiveen
Java tut1 Coderdojo CahersiveenJava tut1 Coderdojo Cahersiveen
Java tut1 Coderdojo Cahersiveen
 

Recently uploaded

The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxLoriGlavin3
 
A Framework for Development in the AI Age
A Framework for Development in the AI AgeA Framework for Development in the AI Age
A Framework for Development in the AI AgeCprime
 
Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Hiroshi SHIBATA
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxLoriGlavin3
 
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...Wes McKinney
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfLoriGlavin3
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesThousandEyes
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
2024 April Patch Tuesday
2024 April Patch Tuesday2024 April Patch Tuesday
2024 April Patch TuesdayIvanti
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxLoriGlavin3
 
Assure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyesAssure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyesThousandEyes
 
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Alkin Tezuysal
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsNathaniel Shimoni
 
Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rick Flair
 
Sample pptx for embedding into website for demo
Sample pptx for embedding into website for demoSample pptx for embedding into website for demo
Sample pptx for embedding into website for demoHarshalMandlekar2
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxLoriGlavin3
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxLoriGlavin3
 

Recently uploaded (20)

The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptx
 
A Framework for Development in the AI Age
A Framework for Development in the AI AgeA Framework for Development in the AI Age
A Framework for Development in the AI Age
 
Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
 
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdf
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
2024 April Patch Tuesday
2024 April Patch Tuesday2024 April Patch Tuesday
2024 April Patch Tuesday
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
 
Assure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyesAssure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyes
 
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directions
 
Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...
 
Sample pptx for embedding into website for demo
Sample pptx for embedding into website for demoSample pptx for embedding into website for demo
Sample pptx for embedding into website for demo
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
 

Cascadia.js: Don't Cross the Streams

  • 1. Don’t Cross the Streams… Matthew Podwysocki @mattpodwysocki
  • 2.
  • 3. Callback Hell… app.get('/index', function (req, res, next) { User.get(req.params.userId, function (err, user) { if (err) next(err); db.find({user: user.name}, function (err, cursor) { if (err) next(err); cursor.toArray(function (err, items) { if (err) next(err); res.send(items); }); }); }); }); …and the Pyramid of Doom
  • 4. The promise of a better future… tweetsAsync() .then(function (a) { return usersAsync(a); }) .then(function (b) { return locationAsync(b); }) .done(function (c) { render(); });
  • 5. What about events? • What about composition? • How do I clean up handlers? • How do I merge streams? • Or filter? • Or aggregate? • Without having a lot of state hanging around? • The list goes on and on…
  • 6. In other words… We cross the streams!
  • 7. What is it? • RxJS is… • a set of types representing asynchronous data streams • a set of operators over asynchronous data streams • a set of types to parameterize concurrency RxJS = Observables + LINQ + Schedulers
  • 8. Not another flow control library… Why bother?
  • 9. var mousedrag = mousedown.selectMany(function (md) { // calculate offsets when mouse down var startX = md.offsetX, startY = md.offsetY; // calculate diffs until mouse up return mousemove.select(function (mm) { return { left: mm.clientX - startX, top: mm.clientY - startY }; }).takeUntil(mouseup); }); Rich Composite Events…
  • 10. var words = Rx.Observable.fromEvent(input, "keyup") .select(function(x) { return input.value; }) .throttle(500) .distinctUntilChanged() .select(function(term) { return search(term); }) .switchLatest(); words.subscribe(function (data) { // Bind data to the UI }); Control Flow…
  • 11. stockTicks .groupBy(function (tick) { return tick.symbol; }) .selectMany( function (g) { return g.bufferWithCount(2, 1); }, function (g, b) { return { key: g.key, b: b }; }) .select(function (c) { return { diff: (c.b[1] – c.b[0]) / c.b[0], symbol: c.key }; }) .where(function (c) { return c.diff > 0.1; }) .select(function (c) { return { company: c.symbol, increase: c.diff }; }); Complex Event Processing…
  • 12. var sequence = '38,38,40,40,37,39,37,39,66,65'; var keyups = Rx.Observable.fromEvent(document, 'keyup') .select(function (x) { return x.keyCode; }) .bufferWithCount(10, 10) .subscribe(function (x) { var matches = x.join() === sequence; if (matches) console.log('Konami'); });
  • 13. What is it? • RxJS is… • a set of types representing asynchronous data streams • a set of operators over asynchronous data streams • a set of types to parameterize concurrency RxJS = Observables + LINQ + Schedulers
  • 14. The Essentials… Observer = { onNext : function (data) { … }, Observable = { onError : subscribe : function (error) { … }, function (observer) { … } onCompleted : }; function () { … } }; Observable Subscribe Observer
  • 15. The Grammar Police… • Zero or more values * ( OnError | OnCompleted ) ? • E.g. events are ∞ sequences 0 1 2 0 1 • It’s a sequence 0 1 2 • No concurrent callbacks • One time termination 0 1 2
  • 17. What? • RxJS is… • a set of types representing asynchronous data streams • a set of operators over asynchronous data streams • a set of types to parameterize concurrency RxJS = Observables + LINQ + Schedulers
  • 18. If you know ES5 Array “extras”… Array Observable • Querying • Querying • concat • concat • every • all • filter • where • map • select • reduce • aggregate • some • any • Subscribing • Subscribing • forEach • subscribe … then you know RxJS
  • 19. Querying Asynchronous Streams • Observables are data streams • Hence we can query them like we do with Arrays! function return
  • 20. Querying Asynchronous Streams • Observables are asynchronous • Hence, they have a notion of time
  • 21. Limited only by imagination… aggregate generateWithRelativeTime selectMany all groupBy sequenceEqual amb skip groupByUntil skipLast any groupJoin skipUntil asObservable skipWhile average ignoreElements interval start buffer startWith join subscribe bufferWithCount bufferWithTime materialize subscribeOn max sum bufferWithTimeOrCount switchLatest catchException maxBy take combineLatest merge takeLast concat mergeObservable takeLastBuffer concatObservable min takeUntil contains minBy takeWhile count multicast then create throttle never throwException createWithDisposable defaultIfEmpty observeOn timeInterval onErrorResumeNext timeout defer timer delay publish using dematerialize publishLast when distinct range where disinctUntilChanged refCount window doAction repeat windowWithCount elementAt windowWithAbsoluteTime elementAtOrDefault replay windowWithRelativeTime empty retry zip generate returnValue generateWithAbsoluteTime sample scan select
  • 22. Creation operators create* empty fromArray generate* never range repeat returnValue
  • 23. Standard operators distinct distinctUntilChanged groupBy select selectMany skip* take* where
  • 24. Aggregation operators aggregate all any contains count min max scan
  • 25. Error handling operators catchException finallyAction onErrorResumeNext retry throwException using
  • 26. Complex Event operators buffer* groupJoin join window* sample
  • 27. Orchestration operators combineLatest concat forkJoin merge skipUntil switchLatest takeUntil zip
  • 28. Time based operators delay interval throttle timeout timeInterval timer timeStamp
  • 29. What? • RxJS is… • a set of types representing asynchronous data streams • a set of operators over asynchronous data streams • a set of types to parameterize concurrency RxJS = Observables + LINQ + Schedulers
  • 30. The Role of Schedulers… Many implementations • Key questions: Cancellation • How to run timers? • Where to produce events? d = scheduler.schedule( function () { • Need to synchronize with the UI? // Asynchronously // running work • Providing one answer: }, • Schedulers introduce concurrency 1000); • Operators are parameterized by schedulers Optional time • Provides test benefits as well
  • 31. var scheduler = new TestScheduler(); var input = scheduler.createColdObservable( onNext(300, "Cascadia"), onNext(400, "JS"), onCompleted(500)); var results = scheduler.startWithCreate(function () { input.select(function (x) { return x.length; }) }); results.messages.assertEqual( onNext(300, 8), onNext(400, 2), Testability is King! onCompleted(500));
  • 32. Start using it now Node.js > npm install rx NuGet > Install-Package RxJS Open Source http://rx.codeplex.com/
  • 33. What’s Next? • Ongoing work • Documentation • Tutorials • Where’s the vision? • Scaling • Distributed • Merge with Node.js Streams
  • 34. Cross the Streams… Matthew Podwysocki @mattpodwysocki matthewp@microsoft.com
  • 35. Credits • Cross the Streams - https://oshea12566.wordpress.com/2012/02/20/jeep-meeting-and- trail-ride/ • NES Controller - http://en.wikipedia.org/wiki/File:NES-controller.jpg