Upgrade to Pro — share decks privately, control downloads, hide ads and more …

RxJS: Reactive If-Else Handling

RxJS: Reactive If-Else Handling

RxJS is one of the tools that makes writing reactive JavaScript pure joy. Learn how to handle if-else branching with a cool Rx pattern and visualize it with Emoji!

Jakub Barczyk

August 31, 2018
Tweet

More Decks by Jakub Barczyk

Other Decks in Programming

Transcript

  1. Reactive programming A programming paradigm concerned with data streams and

    change propagation. With this paradigm it is possible to express and manipulate dynamic (e.g. event emitters) or static (e.g. arrays) data streams.
  2. What is RxJS? Reactive Extensions for JavaScript is a library

    for transforming, composing, and querying streams of data. See: https://rxjs-dev.firebaseapp.com/
  3. What is RxJS? const { of } = Rx; const

    numbers = of(1, 2, 3); numbers.subscribe(num => console.log(num)) OBSERVABLE SUBSCRIBER 3 2 1
  4. const calls = [ { who: 'boss' }, { who:

    'spouse' }, { who: 'unknown' }, { who: 'mum' }, ... ]; const phoneCalls = zip( interval(1000), from(calls) ).pipe(map(([_, call]) => call)); CODE!
  5. The if-else problem MAPPING OBSERVABLE SUBSCRIBER map(({ who }) =>

    { if (who === ‘mum’) return ‘ ’; if (who === ‘boss’) return ‘ ’; ... else return ‘ ’; })
  6. phoneCalls.pipe( map(({ who }) => { if (who === ‘mum’)

    return ‘ ’; if (who === ‘boss’) return ‘ ’; if (who === ‘spouse’) return ‘ ’; /** * * More response conditions here * */ else return ‘ ’; }) ); CODE!
  7. phoneCalls.pipe( tap(({ who }) => { if (who === ‘mum’)

    doSomething(); ... else doSomethingElse(); }), map(({ who }) => { if (who === ‘mum’) return ‘ ’; ... else return ‘ ’; }) ); CODE!
  8. phoneCalls.pipe( tap(({ who }) => { if (who === ‘mum’)

    doSomething(); ... else doSomethignElse(); }), map(({ who }) => { if (who === ‘mum’) return ‘ ’; ... else return ‘ ’; }) ); CODE!
  9. Reactive if-else pattern MUM const mumResponder = phoneCalls.pipe( filter(({ who

    }) => who === ‘mum’), map(() => ‘ ’), tap(() => textBack(‘Yes mum...’)) );
  10. Reactive if-else pattern MUM const mumResponder = phoneCalls.pipe( filter(({ who

    }) => who === ‘mum’), map(() => ‘ ’), tap(() => textBack(‘Yes mum...’)) ); BOSS const bossResponder = phoneCalls.pipe( filter(({ who }) => who === ‘boss’), map(() => ‘ ’) );