Ce diaporama a bien été signalé.
Nous utilisons votre profil LinkedIn et vos données d’activité pour vous proposer des publicités personnalisées et pertinentes. Vous pouvez changer vos préférences de publicités à tout moment.

RxJS: A Better Way to Write Front-End Applications

61 vues

Publié le

Video and slides synchronized, mp3 and slide download available at URL http://bit.ly/2YLwFfs.

Hannah Howard talks about the premise of functional reactive programming. Data itself is treated as asynchronous - as streams which represent a snapshot, a given value over time, and operations that can transform those values. Functional reactive programming is a major conceptual shift but one that can vastly simplify front-end programming. Filmed at qconsf.com.

Hannah Howard is a senior developer and tech generalist with over 15 years experience in programming and other technical fields. Currently, she works at Carbon Five.

Publié dans : Technologie
  • Soyez le premier à commenter

  • Soyez le premier à aimer ceci

RxJS: A Better Way to Write Front-End Applications

  1. 1. @techgirlwonder she/her hannah@carbon ve.com Personal Anecdote: I have a dog HANNAH HOWARD #ABOUTME
  2. 2. InfoQ.com: News & Community Site • Over 1,000,000 software developers, architects and CTOs read the site world- wide every month • 250,000 senior developers subscribe to our weekly newsletter • Published in 4 languages (English, Chinese, Japanese and Brazilian Portuguese) • Post content from our QCon conferences • 2 dedicated podcast channels: The InfoQ Podcast, with a focus on Architecture and The Engineering Culture Podcast, with a focus on building • 96 deep dives on innovative topics packed as downloadable emags and minibooks • Over 40 new content items per week Watch the video with slide synchronization on InfoQ.com! https://www.infoq.com/presentations/ rxjs-front-end/
  3. 3. Purpose of QCon - to empower software development by facilitating the spread of knowledge and innovation Strategy - practitioner-driven conference designed for YOU: influencers of change and innovation in your teams - speakers and topics driving the evolution and innovation - connecting and catalyzing the influencers and innovators Highlights - attended by more than 12,000 delegates since 2007 - held in 9 cities worldwide Presented at QCon San Francisco www.qconsf.com
  4. 4. REACTIVE PROGRAMMING: A Better Way to Write Frontend Applications
  5. 5. 1. PROBLEM STATEMENT
  6. 6. WHAT IS A COMPUTER PROGRAM?
  7. 7. A computer program is a sequence of instructions for performing a task designed to solve speci c problems. - Wikipedia
  8. 8. Program = Todo List? 'SEQUENCE OF INSTRUCTIONS'
  9. 9. LESSON PLAN
  10. 10. HOW COMPUTER PROGRAMS ACTUALLY RUN
  11. 11. the heart of frontend programming INTERRUPTIONS:
  12. 12. 2. A BRIEF HISTORY OF INTERRUPTIONS
  13. 13. Technique 1: GLOBAL EVENT BUS
  14. 14. In The Beginning... C!   1. #define BYTE unsigned char   2. #define NUM_SCAN_QUE 256 // this MUST be 256, using BYTE  roll­over for    3.                          // q code   4. BYTE gb_scan;   5. BYTE gb_scan_q[NUM_SCAN_QUE];   6. BYTE gb_scan_head;   7. BYTE gb_scan_tail;   8.    9. static void interrupt(far *oldkb)(void); /* BIOS keyboard  handler */  10.   11. /* ­­­­­­­­­­­­­­­­­­­­­­ get_scan() ­­­­­­­­­­­­­­­­­­­­­  April 17,1993 */  12. void interrupt get_scan(void)  13. {  14.   /* read the scan code from the keyboard */
  15. 15. Windows event loop   1. int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE  hPrevInstance, LPSTR lpCmdLine, int nCmdShow)   2. {   3.   MSG msg;   4.   BOOL bRet;   5.    6.   while (1)   7.   {   8.     bRet = GetMessage(&msg, NULL, 0, 0);   9.   10.     if (bRet > 0) // (bRet > 0 indicates a message that  must be processed.)  11.     {  12.       TranslateMessage(&msg);  13.       DispatchMessage(&msg);
  16. 16.   1. LRESULT CALLBACK MainWndProc(HWND hwnd, UINT uMsg, WPARAM  wParam, LPARAM lParam) // second message parameter   2. {   3.   switch (uMsg)   4.   {   5.   case WM_CREATE:   6.     // Initialize the window.   7.     return 0;   8.    9.   case WM_PAINT:  10.     // Paint the window's client area.  11.     return 0;  12.   13.   case WM_SIZE:  14.     // Set the size and position of the window.  15.     return 0;  16.   17.   case WM_DESTROY:  18.     // Clean up window­specific data objects.  19.     return 0;  20.   // Window procedure = read message, update state
  17. 17. 1999?
  18. 18.   1. LRESULT CALLBACK MainWndProc(HWND hwnd, UINT uMsg, WPARAM  wParam, LPARAM lParam) // second message parameter   2. {   3.   switch (uMsg)   4.   {   5.   case WM_CREATE:   6.     // Initialize the window.   7.     return 0;   8.    9.   case WM_PAINT:  10.     // Paint the window's client area.  11.     return 0;  12.   13.   case WM_SIZE:  14.     // Set the size and position of the window.  15.     return 0;  16.   17.   case WM_DESTROY:  18.     // Clean up window­specific data objects.  19.     return 0;  20.   //  21.   // Process other messages.  22.   // 23. default: Or did we?
  19. 19.   1. function todoApp(state = initialState, action) {   2.   switch (action.type) {   3.     case SET_VISIBILITY_FILTER:   4.       return { ...state,   5.         visibilityFilter: action.filter   6.       };   7.     case ADD_TODO:   8.       return { ...state,   9.         todos: [
  20. 20. NO SHADE TO REDUX
  21. 21. Technique 2: OBSERVER PATTERN
  22. 22. A SHORT DIGRESSION...
  23. 23. VERY IMPORTANT CONTENT CREATOR
  24. 24. HOW WILL PEOPLE SEE MY CONTENT?
  25. 25. OLD SCHOOL WAY
  26. 26. I will make content - in uencer I will subscribe to your content - adoring fan I made new content - in uencer I am noti ed about your content, and can watch it - adoring fan
  27. 27. I will emit events - Subject I will subscribe to your events - Observer An event happened - Subject I am noti ed about the event, and can handle it - Observer
  28. 28. Real World Example   1. // Function to change the content of t2   2. const modifyText = () => {   3.   const toggle = document.getElementById("toggle");   4.   toggle.firstChild.nodeValue = t2.firstChild.nodeValue ==  "on" ? "off" : "on";   5. }   6.    7. // add event listener to table   8. const el = document.getElementById("toggle­switch");   9. el.addEventListener("click", modifyText, false);
  29. 29. OBSERVER PATTERN VS GLOBAL EVENT BUS (+) Way simpler than global event bus (+) Localized scope (-) Have To Setup Subscriptions
  30. 30. Take home quiz: TRY DRAG AND DROP
  31. 31. MIXING CONCERNS 1. Handling events 2. Subscribing observers
  32. 32. Is this what happened? REDUX ORIGIN STORY
  33. 33. IS THERE A BETTER WAY?
  34. 34. 3. FUNCTIONAL REACTIVE PROGRAMMING
  35. 35. I taught middle school ONCE UPON A TIME...
  36. 36. GOOD TEACHERS = JEDI
  37. 37. DON'T START WITH A PLAN...
  38. 38. AND GET INTERRUPTED.
  39. 39. PLAN FOR INTERRUPTIONS AND REACT!
  40. 40. PSA: PAY TEACHERS
  41. 41. HOW COULD WE WRITE PROGRAMS REACTIVELY?
  42. 42. Consider this statement Y = X + 3
  43. 43. Assign once the value for y by adding 3 to x IMPERATIVE MEANING:
  44. 44. An equation MATH MEANING 5 10 15 20­5­10­15­20 5 10 15 20 ­5 ­10 ­15 ­20 y x
  45. 45. X is a value that can change over time. Y is always the value 3 greater than X REACTIVE MEANING:
  46. 46. a data stream of numbers over time X VALUES OVER TIME 0 9 3 10 4
  47. 47. a data stream of numbers derived from another stream Y VALUES OVER TIME 0 9 3 10 4 3 12 6 13 7
  48. 48. Stream of user input events MOUSE CLICKS OVER TIME MC MC MCMCMCMC MC MCMCMCMC MC
  49. 49. REACTIVE PROGRAMMING IN THE REAL WORLD?
  50. 50. Only better... OBSERVER PATTERN!
  51. 51. A value that changes over time, that we can listen to changes on OBSERVABLE:
  52. 52. Value as 'Observable'   1. x.subscribe(nextX => console.log(nextX))   2.    3. x.subscribe(nextX => console.log(nextX + 3))   4.    5. y = "?";   6.    7. x = [0, 9, 3, 10, 4]   8.    9. y = x.map(nextX => nextX + 3)  10.   11. x = Observable.of(0, 9, 3, 10, 4);  12.   13. y = x.map(nextX => nextX + 3)
  53. 53. Go Left Go Right Left Button Clicks Right Button Clicks Left Click Position Right Click Position Position
  54. 54. How This Works   1. import {   2.   fromEvent,   3.   merge   4. } from "rxjs";
  55. 55. 4. HOW DO I ACTUALLY USE THIS?
  56. 56. IMPORTANT DATA POINT
  57. 57. YOU'RE ALREADY USING IT.
  58. 58. TWO QUESTIONS FOR USING RXJS How to architect applications with RxJS? How do I integrate this in my application, today?
  59. 59. User name: Password: Submit User name Password Submit Button Login Attempts Login Responses Login In ProgressLogin Failures Login Successes Failure Message User Token Get Protected Protected Resourc
  60. 60. But how tho?   1. const api = {   2.   login: (username, password) => Promise,   3.   protectedResource: {   4.     get: (userToken) => Promise   5.   }   6. };   7.    8. const username$ = new Subject();   9. const password$ = new Subject();  10. const submitButton$ = new Subject();  11.   12. const loginAttempts$ =  submitButton$.pipe(withLatestFrom(username$, password$));  13.   14. const loginResponses$ = loginAttempts$.pipe(  15.   mergeMap(([_, username, password]) => api.login(  16.     username, 17. password
  61. 61. How data propogates through your program SIGNAL GRAPH
  62. 62. ACTUAL SIGNAL GRAPH FROM REAL APP email passwordauthorizationRequested selectedAccountIndex portfolioSelectedauthorization user failedLogins portfolios activePortfolio portfolioSecurities accounts activeAccount activeAccountPerformances activeAccountPortfolios
  63. 63. PRODUCTION CONCERNS 1. How do I test? 2. How do I make sure my graph is sound? 3. Ack RxJs idiosyncracies! 4. One big graph or lots of smaller ones? 5. Diagramming is hard
  64. 64. I liked Signal Graphs so much I bought the company! - me, 2018
  65. 65. A library for frontend state management using signal graphs SIGNAL:
  66. 66. Signal!   1. const signalGraph = new SignalGraphBuilder()   2.   .define(   3.     addPrimary('username$'),   4.     addPrimary('password$'),   5.     addPrimary('submitButton$'),   6.     addDerived(   7.       'loginAttempts$',   8.       makeLoginAttempts,   9.       'submitButton$',  10.       'username$',  11.       'password$'  12.     ),  13.     addDerived('loginResponses$', makeLoginResponses,  'loginAttempts$', 'api'),  14.     addDerived(  15.       'loginInProgress$',  16.       makeLoginInProgress, 17. 'loginAttempts$',
  67. 67. Available Now(ish): @RXREACT/SIGNAL
  68. 68. Coming Soon: AUTOMATIC GRAPH VISUALIZATION
  69. 69. INTEGRATION
  70. 70. FRAMEWORK = ANGULAR 1. You're done 2. Check out NgRx
  71. 71. BUT WHAT ABOUT REACT?
  72. 72. GOOD NEWS!
  73. 73. Tools for integrating react with RxJs! RXREACT:
  74. 74. Signal-connect   1. import { withViewModel } from '@rxreact/signal­connect'   2.    3. const PositionedBox = ({ position }) => <RedBox pose= {position} />   4.    5. const ballSignalGraph = new  SignalGraphBuilder().define(/*...*/).build()   6.    7. // connect(graph, mapGraphOutputsToProps,  mapGraphInputsToProps = {})   8. const BoundBox = connect(   9.   ballSignalGraph,  10.   {  11.     position: 'position$'  12.   }  13. )(PositionedBox)  14.  15. const LeftButton = connect(
  75. 75. 5. USED CAR SALES PORTION
  76. 76. RxJs+React on it's own @RXREACT/CORE:
  77. 77. RxReact Demo   1. import { withViewModel } from '@rxreact/core'   2.    3. const PositionedBox = ({ position }) => <RedBox pose= {position} />   4.    5. const boxVm = {   6.   inputs: {   7.     position: position$   8.   }   9. }  10.   11. const BoundBox = withViewModel(boxVm)(PositionedBox)  12.   13. const LeftButton = withViewModel({  14.   outputs: {  15.     onClick: leftClick$  16.   }
  78. 78. WHAT ABOUT TYPESCRIPT?
  79. 79. RXREACT TYPESCRIPT
  80. 80. VIEW MODEL AS REDUCER?
  81. 81.   1. let viewModel = viewModelFromReducer({   2.   initialState: {   3.     count: 2,   4.     fruit: 'bananas',   5.     extra: 'applesauce'   6.   },   7.   reducer(state, action) {   8.     switch (action.type) {   9.       case ActionType.SET_COUNT:  10.         return ReducerResult.Update({ ...state,  11.           count: action.payload
  82. 82. @RXREACT/PROCESS
  83. 83. reactivex-talk.techgirlwonder.com github.com/hannahhoward/reactivex-talk THAT'S ALL FOLKS!
  84. 84. Watch the video with slide synchronization on InfoQ.com! https://www.infoq.com/presentations/ rxjs-front-end/

×