Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.
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) {
      ...
The promise of a better future…


tweetsAsync()
    .then(function (a) { return usersAsync(a); })
    .then(function (b) {...
What about events?
• What about composition?
• How do I clean up handlers?
• How do I merge streams?
• Or filter?
• Or agg...
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 ...
Not another flow control library…

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

      // calculate offsets when mouse down
      var startX = md.off...
var words = Rx.Observable.fromEvent(input, "keyup")
            .select(function(x) { return input.value; })
            ....
stockTicks
  .groupBy(function (tick) { return tick.symbol; })
  .selectMany(
    function (g) { return g.bufferWithCount(...
var sequence = '38,38,40,40,37,39,37,39,66,65';

var keyups = Rx.Observable.fromEvent(document, 'keyup')
     .select(func...
What is it?
• RxJS is…
  • a set of types representing asynchronous data streams
  • a set of operators over asynchronous ...
The Essentials…
Observer = {
  onNext :
    function (data) { … },        Observable = {
  onError :                      ...
The Grammar Police…

•   Zero or more values
                       *          ( OnError       | OnCompleted ) ?
•   E.g. ...
First Class Events…
What?
• RxJS is…
  • a set of types representing asynchronous data streams
  • a set of operators over asynchronous data s...
If you know ES5 Array “extras”…
Array              Observable
• Querying         • Querying
   •    concat        •   conc...
Querying Asynchronous Streams

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



    ...
Querying Asynchronous Streams

• Observables are asynchronous
  • Hence, they have a notion of time
Limited only by imagination…
aggregate                   generateWithRelativeTime   selectMany
all                        ...
Creation operators
                   create*
                   empty
                 fromArray
                 generat...
Standard operators
                     distinct
             distinctUntilChanged
                    groupBy
           ...
Aggregation operators
                aggregate
                    all
                   any
                 contains
 ...
Error handling operators

                catchException
                  finallyAction
              onErrorResumeNext
 ...
Complex Event operators


                 buffer*
                groupJoin
                   join
                windo...
Orchestration operators
               combineLatest
                   concat
                  forkJoin
                ...
Time based operators

                    delay
                  interval
                  throttle
                  ti...
What?
• RxJS is…
  • a set of types representing asynchronous data streams
  • a set of operators over asynchronous data s...
The Role of Schedulers…
                                                          Many
                                   ...
var scheduler = new TestScheduler();

var input = scheduler.createColdObservable(
    onNext(300, "Cascadia"),
    onNext(...
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 ...
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 Controll...
Cascadia.js: Don't Cross the Streams
You’ve finished this document.
Download and read it offline.
Upcoming SlideShare
NDC14 - Rx와 Functional Reactive Programming으로 고성능 서버 만들기
Next
Upcoming SlideShare
NDC14 - Rx와 Functional Reactive Programming으로 고성능 서버 만들기
Next
Download to read offline and view in fullscreen.

17

Share

Cascadia.js: Don't Cross the Streams

Download to read offline

Introduction to the Reactive Extensions for JavaScript at Cascadia JS 2012

Related Books

Free with a 30 day trial from Scribd

See all

Related Audiobooks

Free with a 30 day trial from Scribd

See all

Cascadia.js: Don't Cross the Streams

  1. 1. Don’t Cross the Streams… Matthew Podwysocki @mattpodwysocki
  2. 2. 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
  3. 3. The promise of a better future… tweetsAsync() .then(function (a) { return usersAsync(a); }) .then(function (b) { return locationAsync(b); }) .done(function (c) { render(); });
  4. 4. 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…
  5. 5. In other words… We cross the streams!
  6. 6. 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
  7. 7. Not another flow control library… Why bother?
  8. 8. 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…
  9. 9. 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…
  10. 10. 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…
  11. 11. 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'); });
  12. 12. 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
  13. 13. The Essentials… Observer = { onNext : function (data) { … }, Observable = { onError : subscribe : function (error) { … }, function (observer) { … } onCompleted : }; function () { … } }; Observable Subscribe Observer
  14. 14. 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
  15. 15. First Class Events…
  16. 16. 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
  17. 17. 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
  18. 18. Querying Asynchronous Streams • Observables are data streams • Hence we can query them like we do with Arrays! function return
  19. 19. Querying Asynchronous Streams • Observables are asynchronous • Hence, they have a notion of time
  20. 20. 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
  21. 21. Creation operators create* empty fromArray generate* never range repeat returnValue
  22. 22. Standard operators distinct distinctUntilChanged groupBy select selectMany skip* take* where
  23. 23. Aggregation operators aggregate all any contains count min max scan
  24. 24. Error handling operators catchException finallyAction onErrorResumeNext retry throwException using
  25. 25. Complex Event operators buffer* groupJoin join window* sample
  26. 26. Orchestration operators combineLatest concat forkJoin merge skipUntil switchLatest takeUntil zip
  27. 27. Time based operators delay interval throttle timeout timeInterval timer timeStamp
  28. 28. 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
  29. 29. 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
  30. 30. 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));
  31. 31. Start using it now Node.js > npm install rx NuGet > Install-Package RxJS Open Source http://rx.codeplex.com/
  32. 32. What’s Next? • Ongoing work • Documentation • Tutorials • Where’s the vision? • Scaling • Distributed • Merge with Node.js Streams
  33. 33. Cross the Streams… Matthew Podwysocki @mattpodwysocki matthewp@microsoft.com
  34. 34. 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
  • formesaid

    Aug. 20, 2020
  • ThiHcNguyn

    Aug. 31, 2019
  • DongSungShin1

    Oct. 18, 2017
  • tinh357

    Nov. 7, 2016
  • bbkingtw

    Jun. 14, 2016
  • micus74

    Apr. 28, 2016
  • dfdgsdfg

    Apr. 5, 2016
  • KiwoongShin

    Jan. 19, 2016
  • esneko

    Dec. 16, 2015
  • hmpop

    Jun. 9, 2015
  • enzuguri

    May. 5, 2015
  • smorghead

    Apr. 15, 2015
  • awnstudio

    Jan. 25, 2015
  • reflex99

    Jan. 9, 2015
  • ryangasparini

    Oct. 3, 2014
  • mhaidarhanif

    Oct. 3, 2014
  • Talbott

    Nov. 9, 2012

Introduction to the Reactive Extensions for JavaScript at Cascadia JS 2012

Views

Total views

37,554

On Slideshare

0

From embeds

0

Number of embeds

27,333

Actions

Downloads

90

Shares

0

Comments

0

Likes

17

×