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.

Reactive Programming - ReactFoo 2020 - Aziz Khambati

What does it mean to be Reactive?

  • Be the first to comment

  • Be the first to like this

Reactive Programming - ReactFoo 2020 - Aziz Khambati

  1. 1. REACTIVE PROGRAMMING WHAT DOES IT MEAN TO BE REACTIVE?
  2. 2. ABOUT ME ▸ Aziz Khambati ▸ Frontend Developer at Anarock Tech, Mumbai ▸ Blog - https://medium.com/@azizhk
  3. 3. AGENDA ▸ Intro to Reactive Programming ▸ Advantages ▸ React ▸ Extent ▸ Observables & Rx.js ▸ Future
  4. 4. DECLARATIVE PROGRAMMING PARADIGM CONCERNED WITH DATA STREAMS AND THE PROPAGATION OF CHANGE. https://en.wikipedia.org/wiki/Reactive_programming REACTIVE PROGRAMMING
  5. 5. STYLE OF BUILDING THE STRUCTURE AND ELEMENTS OF COMPUTER PROGRAMS THAT EXPRESSES THE LOGIC OF A COMPUTATION WITHOUT DESCRIBING ITS CONTROL FLOW. https://en.wikipedia.org/wiki/Declarative_programming DECLARATIVE PROGRAMMING
  6. 6. SPREADSHEETS CLASSIC EXAMPLE
  7. 7. IMPERATIVE PROGRAMMING Spreadsheet data flow + logic
 Code for illustration, not actual code const globalBus = createPubSubBus(); class Cell { constructor() { this.compute(); globalBus.subscribe("B2", this.compute); globalBus.subscribe("C2", this.compute); } compute () { const qty = getValue("B2"); const price = getValue("C2"); const value = qty * price; globalBus.publish("D2", value); } }
  8. 8. SPREADSHEETS API ▸ Formula shows how value is computed — Declarative ▸ No need to write code to listen for changes ▸ Changes are propagated. Reactive }
  9. 9. WHY DID REACT GET SO POPULAR?
  10. 10. WHY DID REACT GET SO POPULAR? ▸ Fast VDOM ▸ Event Delegation (Synthetic Events) ▸ Ability to split into Components ▸ JSX ▸ Target multiple platforms (Web, Android, iOS) ▸ ?
  11. 11. TEMPLATING LANGUAGE BASED COMPONENTS (FROM TODOMVC BACKBONE EXAMPLE) .view input.toggle( type='checkbox' checked=completed ) label !#{title} button.destroy input.edit(value=title)
  12. 12. TEMPLATING LANGUAGE BASED COMPONENTS const TodoView = Backbone.View.extend({ tagName: 'li', template: _.template($('#item-template').html()), events: { 'click .toggle': 'toggleVisible', }, initialize: function () { this.listenTo(this.model, 'visible', this.toggleVisible); }, toggleVisible: function () { this.$el.toggleAttr('checked'); } }); Poor Separation of Concern
  13. 13. REACT TEMPLATE - DOM AS A FUNCTION OF THE STATE class TodoItem extends React.Component { !!... render () { const { completed, title } = this.state return ( !<> <div class="view"> <input class="toggle" type="checkbox" checked={completed} onChange={this.onToggle} > <label>{title}!</label> <button class="destroy">!</button> !</div> <input class="edit" value={title} !/> !!</> ); } JSX & VDOM
 created to support
 Declarative API
  14. 14. BENEFITS ▸ No need to write code to modify individual attributes of DOM ▸ Easy to Read - Declarative Programming of the DOM ▸ Easy to test - Side Effects Free View ▸ Tools like Enzyme allowed Testing without a browser
  15. 15. REACT - JUST THE VIEW LAYER No Declarative API for 
 Data Flow class TodoItem extends React.Component { !!... render () { const { completed, title } = this.state return ( !<> <div class="view"> <input class="toggle" type="checkbox" checked={completed} onChange={this.onToggle} > <label>{title}!</label> <button class="destroy">!</button> !</div> <input class="edit" value={title} !/> !!</> ); }
  16. 16. REACTIVITY WITH APOLLO GRAPHQL export default graphql(gql` query TodoAppQuery { todos { id text } } `)(function TodoApp({ data: { todos } }) { return ( <ul> {todos.map(({ id, text }) !=> ( <li key={id}>{text}!</li> ))} !</ul> ); });
  17. 17. AUTOSUGGEST COMPONENT EXAMPLE
  18. 18. class Autocomplete extends React.PureComponent { state = { suggestions: [] }; render() { return ( !<> <input !/> <ul> {this.state.suggestions.map(s !=> ( <li key={s.id}>{s.label}!</li> ))} !</ul> !!</> ); } }
  19. 19. class Autocomplete extends React.PureComponent { state = { suggestions: [] }; onInputChange = async e !=> { const data = await fetch(`example.com/api?q=${e.target.value}`); this.setState({ suggestions: data }); }; render() { return ( !<> <input onChange={this.onInputChange} !/> <ul> {this.state.suggestions.map(s !=> ( <li key={s.id}>{s.label}!</li> ))} !</ul> !!</> ); }
  20. 20. class Autocomplete extends React.PureComponent { state = { suggestions: [] }; onInputChange = _.debounce(async e !=> { const data = await fetch(`example.com/api?q=${e.target.value}`); this.setState({ suggestions: data }); }, 500); render() { return ( !<> <input onChange={this.onInputChange} !/> <ul> {this.state.suggestions.map(s !=> ( <li key={s.id}>{s.label}!</li> ))} !</ul> !!</> ); }
  21. 21. class Autocomplete extends React.PureComponent { state = { suggestions: [] }; apiController = null; onInputChange = _.debounce(async e !=> { if (this.apiController) this.apiController.abort(); this.apiController = new AbortController(); const data = await fetch(`example.com/api?q=${e.target.value}`, { signal: this.apiController }); this.setState({ suggestions: data }); }, 500); render() { return ( !<> <input onChange={this.onInputChange} !/> <ul> {this.state.suggestions.map(s !=> ( <li key={s.id}>{s.label}!</li>
  22. 22. class Autocomplete extends React.PureComponent { state = { suggestions: [] }; apiController = null; onInputChange = _.debounce(async e !=> { if (this.apiController) this.apiController.abort(); this.apiController = new AbortController(); try { const data = await fetch(`example.com/api?q=${e.target.value}`, { signal: this.apiController }); this.setState({ suggestions: data }); } catch (e) { if (e.name !!=== "AbortError") return; throw e; } }, 500); render() { return (
  23. 23. apiController = null; onInputChange = _.debounce(async e !=> { if (this.apiController) this.apiController.abort(); this.apiController = new AbortController(); let trials = 0; while (true) { try { const data = await fetch(`example.com/api?q=${e.target.value}`, { signal: this.apiController }); this.setState({ suggestions: data }); } catch (e) { if (e.name !!=== "AbortError") return; trials!++; if (trials !<= 3) continue; throw e; } } }, 500);
  24. 24. apiController = null; lastSearch = null; onInputChange = _.debounce(async e !=> { if (this.lastSearch !!=== e.target.value) return; this.lastSearch = e.target.value; if (this.apiController) this.apiController.abort(); this.apiController = new AbortController(); let trials = 0; while (true) { try { const data = await fetch(`example.com/api?q=${e.target.value}`, { signal: this.apiController }); this.setState({ suggestions: data }); } catch (e) { if (e.name !!=== "AbortError") return; trials!++; if (trials !<= 3) continue; throw e;
  25. 25. BUILD AN AUTOSUGGEST FEATURE CONFIGURATION ▸ Debounce Input ▸ Fetch Suggestions ▸ Don’t Fetch unless input has changed ▸ Retry on Failures ▸ Cancel Previous Requests ▸ Cancel on unmount. At least 2x number
 of props to configure them.
  26. 26. RX.JS SUPER HERO LANDING
  27. 27. AUTOCOMPLETE ▸ Debounce Input ▸ Fetch Suggestions ▸ Don’t Fetch unless input has changed ▸ Retry on Failures ▸ Cancel Previous Requests ▸ Cancel on unmount. ▸ debounce() ▸ ajax() ▸ distinctUntilChanged() ▸ retry() ▸ switchMap() ▸ .unsubscribe() USING RX.JS
  28. 28. AUTOCOMPLETE USING RXJS const suggestion$ = input$.pipe( debounce(400), distinctUntilChanged(), switchMap((input) !=> ajax({ url: `example.com/autosuggest?q=${input}` }) ), retry(2), map(res !=> res.data) )
  29. 29. DECLARATIVE PROGRAMMING PARADIGM CONCERNED WITH DATA STREAMS AND THE PROPAGATION OF CHANGE. https://en.wikipedia.org/wiki/Reactive_programming REACTIVE PROGRAMMING
  30. 30. BRIEF INTRO TO RXJS ▸ Everything is a stream. ▸ Think of Source, Pipes & Sinks ▸ Pipes can be built independently. ▸ Source can be connected to pipes but no flow without a sink. ▸ If the sink is turned off, the cancellation propagates up to the source.
  31. 31. Single Value Multiple Values Sync Scalar Constant Array Async Promise Observable OBSERVABLE - KEY DATA STRUCTURE IN RX,JS
  32. 32. RX.JS ANALOGY ▸ Observable - Source ▸ Operators - Pipes ▸ Subscriptions - Sinks
  33. 33. AUTOCOMPLETE USING RXJS const suggestion$ = input$.pipe( debounce(400), distinctUntilChanged(), switchMap((input) !=> ajax({ url: `example.com/autosuggest?q=${input}` }) ), retry(2), map(res !=> res.data) )
  34. 34. TEXT USAGE WITH VIEW LIBRARIES ▸ React ▸ observable-hooks ▸ rxjs-hooks ▸ Vue ▸ vue-rx ▸ Angular has built in Rx.js support ▸ Cycle.js is built using Rx.js (soon moving to call bags)
  35. 35. TEXT MY PERSONAL EXPERIENCE ▸ React Native App for Sales Agent to manage clients, client meetings (CRM) ▸ App has 5 Search Boxes (3 over SQLite DB, 2 over HTTP Endpoint) ▸ Never used a AutoSuggest Component. ▸ Used Rx.js to compose various features as every had its own parameters ▸ SQLite DB is also exposed over Rx.js API ▸ Watermelon DB 🍉 FTW!! - Reactive over changes in DB. ▸ redux-observables to handle async Actions
  36. 36. OTHER MATERIALS WHY REACT IS NOT REACTIVE - SHAWN WANG SWYX
  37. 37. TEXT KEY - TAKEAWAYS ▸ Tons of libraries out there, choose your style. ▸ Javascript is limiting and thus every Framework has its compromises ▸ Pick which is ▸ Easy to Read ▸ Easy to Predict ▸ Easy to Debug ▸ Pick a framework for which it is easier to hire.
  38. 38. THANK YOU

    Be the first to comment

What does it mean to be Reactive?

Views

Total views

45

On Slideshare

0

From embeds

0

Number of embeds

0

Actions

Downloads

1

Shares

0

Comments

0

Likes

0

×