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

Clean Android Client Architecture with Rx and MVVM (GDG Kaohsiung #27)

shiami
January 20, 2016

Clean Android Client Architecture with Rx and MVVM (GDG Kaohsiung #27)

shiami

January 20, 2016
Tweet

More Decks by shiami

Other Decks in Programming

Transcript

  1. ANDROID DEV, IOS DEV, PRODUCT DEV, UX DESIGN, SERVICE DESIGN,

    STARTUP, GDG KAOHSIUNG, APP TALK, AND ETC.
  2. TODAY WE WILL TALK ABOUT.. ▸ Review the Issues and

    Challenges in Android Client App Development ▸ Uncle Bob: Clean Architecture ▸ Everything is a Stream - ReactiveX to the Rescue! ▸ The Most Powerful REST Client Library - Retrofit ▸ Android MVVM Pattern - Data Binding Support Library ▸ The Combined Solution - Demo and Recap
  3. TODAY WE WILL TALK ABOUT.. ▸ Review the Issues and

    Challenges in Android Client App Development ▸ Uncle Bob: Clean Architecture ▸ Everything is a Stream - ReactiveX to the Rescue! ▸ The Most Powerful REST Client Library - Retrofit ▸ Android MVVM Pattern - Data Binding Support Library ▸ The Combined Solution - Demo and Recap
  4. WHAT IS AN ACTIVITY OR A FRAGMENT? ▸ Screens (UI)

    ▸ Flows ▸ Fundamental building blocks of Android app ▸ Lifecycle
  5. ACTIVITY LIFECYCLE STATUS ▸ On app startup ▸ On app

    resume ▸ On focus gain ▸ On focus loss ▸ On app swap or device sleep ▸ Orientation changed ▸ Being killed
  6. ACTIVITY LIFECYCLE HANDLING ▸ onCreate(), onStart(), onResume() ▸ onPause(), onStop(),

    onDestroy() ▸ onSaveInstanceState() ▸ Handle activity restart ▸ Handle resource usage ▸ Handle your model status ▸ Handle sync and async tasks
  7. WHAT YOUR PARENTS NEVER TOLD YOU ABOUT FRAGMENTS ▸ Lifecycle

    is too complex ▸ We have to rely solely on default constructors, rather than custom constructors ▸ Nested Fragments are prone to bugs and limitations. ▸ Hard to trace, hard to debug ▸ View controllers? Not easy to decouple views and models ▸ Fragment transactions is async - Unstable state ▸ Fragment recreation problem - Missing outer class
  8. ANOTHER PROBLEM HERE.. ▸ How to communicate activities and fragments?

    ▸ Intent? ▸ onActivityResult()? ▸ Handler? ▸ Broadcast? ▸ Interface?
  9. HOW TO COMMUNICATE ACTIVITIES AND FRAGMENTS? ▸ Not easy to

    communicate ▸ close coupled ▸ boilerplate code ▸ Solution: Event bus ▸ But not easy to manage the event listeners if too many
  10. ADVOCATING AGAINST ANDROID FRAGMENTS ▸ Avoid using fragments ▸ “One

    Activity, Multiple Views” approach ▸ An Investigation into Flow and Mortar
  11. TEXT REAL WORLD ISSUES ABOUT ACTIVITY & FRAGMENT ▸ They

    are UI screens, flow controls, and lifecycles ▸ Put everything in them (Nightmare!) ▸ The code is hard to trace and debug ▸ Strong connection to each other ▸ Hard to do unit test ▸ Mess up with the lifecycle ▸ Especially the next thing we are going to talk about..
  12. WHAT IS AN ANDROID CLIENT APP? ▸ Will connect to

    a backend server on the internet ▸ Network async tasks ▸ REST API calls
  13. TEXT DO NETWORK ASYNC TASKS WITH ANDROID FRAMEWORK ▸ Thread,

    Handler ▸ AsyncTask ▸ IntentService, ResultReceiver ▸ Loader, AsyncTaskLoader
  14. THREAD ▸ Plain old Java Thread ▸ No cancellation policy

    ▸ Hard way to deliver results in UI thread ▸ Nested codes with Handler, Runnable, Looper
  15. ASYNCTASK ▸ Easier usage than Thread ▸ Callbacks for UI

    and background operations ▸ Callback hell ▸ Not bound to activity or fragment lifecycle ▸ Hard to handle errors
  16. …OTHER COMPONENTS? ▸ Volley? ▸ There are also some restrictions

    and problems ▸ Hard to manage for many REST API calls in the real world
  17. ANDROID ASYNC TASK REAL WORLD CHALLENGES ▸ Persistence across configuration

    changes (Context leak) ▸ Strong relationship (Close coupling) ▸ Callback hell ▸ Lack of error handling ▸ Boilerplate codes ▸ Messy, hard-to-trace, maybe-buggy, dirty architecture
  18. ANDROID CLIENT APP DEVELOPMENT RECAP: WE HAVE TWO MAJOR PROBLEMS

    COMBINED TOGETHER ▸ Android lifecycle is too complex, especially with async tasks ▸ Android async tasks are hard to write and manage when firing many RESTful requests
  19. TODAY WE WILL TALK ABOUT.. ▸ Review the Issues and

    Challenges in Android Client App Development ▸ Uncle Bob: Clean Architecture ▸ Everything is a Stream - ReactiveX to the Rescue! ▸ The Most Powerful REST Client Library - Retrofit ▸ Android MVVM Pattern - Data Binding Support Library ▸ The Combined Solution - Demo and Recap
  20. ROBERT CECIL MARTIN (KNOWN AS UNCLE BOB) ▸ An American

    software engineering, author, public speaker ▸ Publications ▸ (2002). Agile software development: principles, patterns, and practices. ▸ (2009). Clean code: a handbook of agile software craftsmanship. ▸ (2011). The clean coder: a code of conduct for professional programmers.
  21. THE CLEAN ARCHITECTURE ▸ The architecture produce a system ▸

    Independent of Frameworks ▸ Testable ▸ Independent of UI ▸ Independent of Database ▸ Independent of any external agency ▸ Independency of each level (Decoupled, Replaceable)
  22. CLEAN ANDROID ARCHITECTURE ▸ Easy to maintain codes ▸ Easy

    to test ▸ Easy to manage relations ▸ Decoupled
  23. TODAY WE WILL TALK ABOUT.. ▸ Review the Issues and

    Challenges in Android Client App Development ▸ Uncle Bob: Clean Architecture ▸ Everything is a Stream - ReactiveX to the Rescue! ▸ The Most Powerful REST Client Library - Retrofit ▸ Android MVVM Pattern - Data Binding Support Library ▸ The Combined Solution - Demo and Recap
  24. TEXT WHAT ARE REACTIVE EXTENSIONS (REACTIVEX, RX) ? ▸ Rx,

    initiated by Erik Meijer (C# and .Net, then adapted to many different languages), is a library that allows you to apply FRP to any language.
  25. IT’S REALLY NOT EASY TO GET INTO IT, BUT.. LET’S

    SPLIT IT UP FIRST! ReactiveX TEXT
  26. REACTIVEX KEYWORDS: ▸ Observer Pattern ▸ Functional programming ▸ Reactive

    programming ▸ FRP (Functional Reactive Programming)
  27. REACTIVEX KEYWORDS: ▸ Observer Pattern ▸ Functional programming ▸ Reactive

    programming ▸ FRP (Functional Reactive Programming)
  28. REACTIVEX KEYWORDS: ▸ Observer Pattern ▸ Functional programming ▸ Reactive

    programming ▸ FRP (Functional Reactive Programming)
  29. IT’S ALMOST CERTAINLY TRUE THAT FUNCTIONAL PROGRAMMING IS THE NEXT

    BIG THING. Uncle Bob HTTPS://PRAGPROG.COM/MAGAZINES/2013-01/FUNCTIONAL-PROGRAMMING-BASICS
  30. FUNCTIONAL PROGRAMMING ▸ Definition on Wikipedia ▸ In computer science,

    functional programming is a programming paradigm—a style of building the structure and elements of computer programs—that treats computation as the evaluation of mathematical functions and avoids changing-state and mutable data.
  31. FUNCTIONAL PROGRAMMING ▸ Definition on Wikipedia ▸ In computer science,

    functional programming is a programming paradigm—a style of building the structure and elements of computer programs—that treats computation as the evaluation of mathematical functions and avoids changing-state and mutable data.
  32. FUNCTIONAL PROGRAMMING ▸ Output o = sqrt(Input); ▸ sqrt() is

    a black box ▸ Modularity ▸ Easy to maintain ▸ Better software architecture
  33. FUNCTIONAL PROGRAMMING ▸ Output o2 = abs(cos(sqrt(Input))); ▸ Separate a

    big problem into several boxes ▸ Easy to test ▸ Focus on data flow
  34. ASYNC ▸ Multi-threading programming is hard ▸ Hard to program

    ▸ Hard to test ▸ Mutable shared state ▸ Complex logic
  35. FUNCTIONAL PROGRAMMING ▸ Definition on Wikipedia ▸ In computer science,

    functional programming is a programming paradigm—a style of building the structure and elements of computer programs—that treats computation as the evaluation of mathematical functions and avoids changing-state and mutable data ▸ Much easier for multithreading programming
  36. FUNCTIONAL PROGRAMMING ▸ Features ▸ First-class functions (Concept) ▸ Function

    as first-class citizen ▸ Allow functions as arguments and results of other functions
  37. TEXT FUNCTIONAL PROGRAMMING EXAMPLE ▸ We have a number list.

    ▸ 1, 2, 3, 5, 7, 9, 11, 12, 13 ▸ Multiply 2, and get the largest number less than 10
  38. MULTIPLY 2, AND GET THE LARGEST NUMBER LESS THAN 10

    TEXT FUNCTIONAL PROGRAMMING EXAMPLE (NORMAL WAY)
  39. MULTIPLY 2, AND GET THE LARGEST NUMBER LESS THAN 10

    FUNCTIONAL PROGRAMMING EXAMPLE (RX WAY)
  40. REACTIVEX KEYWORDS: ▸ Observer Pattern ▸ Functional programming ▸ Reactive

    programming ▸ FRP (Functional Reactive Programming)
  41. REACTIVE PROGRAMMING ▸ Wikipedia ▸ In computing, reactive programming is

    a programming paradigm oriented around data flows and the propagation of change ▸ There are certain datatypes that represent a value "over time"
  42. REACTIVE PROGRAMMING ▸ b = 10, c = 2; ▸

    a = b + c; ▸ b = 5; ▸ > print a ▸ // 12
  43. REACTIVE PROGRAMMING ▸ b = 10, c = 2; ▸

    a = b + c; ▸ b = 5; ▸ > print a ▸ // 7
  44. REACTIVE PROGRAMMING ▸ Data stream on GUI ▸ A mouse

    movement event (Position data stream) ▸ 20:01:35:000 at (200, 200) ▸ 20:01:35:001 at (201, 200) ▸ 20:01:35:002 at (202, 200) ▸ 20:01:35:003 at (203, 200) ▸ 20:01:35:004 at (204, 200) ▸ …
  45. REACTIVE PROGRAMMING ▸ Data stream on GUI ▸ Reactive to

    mouse move ▸ To receive current position ▸ Become a mouse movement event ▸ Reactive to mouse movement event ▸ To change corresponding UI ▸ For example: ▸ Display hint at certain position ▸ Open a menu at certain position
  46. REACTIVE PROGRAMMING ▸ Wikipedia ▸ In computing, reactive programming is

    a programming paradigm oriented around data flows and the propagation of change ▸ There are certain datatypes that represent a value "over time"
  47. REACTIVEX KEYWORDS: ▸ Observer Pattern ▸ Functional programming ▸ Reactive

    programming ▸ FRP (Functional Reactive Programming)
  48. FRP (FUNCTIONAL REACTIVE PROGRAMMING) ▸ Definition on Wikipedia ▸ Functional

    reactive programming (FRP) is a programming paradigm for reactive programming (asynchronous dataflow programming) using the building blocks of functional programming (e.g. map, reduce, filter). ▸ FRP has been used for programming graphical user interfaces (GUIs), robotics, and music, aiming to simplify these problems by explicitly modeling time.
  49. RECAP: WE HAVE TWO MAJOR PROBLEMS COMBINED TOGETHER ▸ Android

    lifecycle is too complex, especially with async tasks ▸ Android async tasks are hard to write and manage when firing many RESTful requests
  50. TEXT SOME TIPS BEFORE START.. ▸ Anonymous class ▸ Enable

    you to declare and instantiate a class at the same time ▸ Use them if you need to use a local class only once
  51. TEXT SOME TIPS BEFORE START.. ▸ Lambda expression ▸ One

    issue with anonymous classes is that if the implementation of your anonymous class is very simple, such as an interface that contains only one method, then the syntax of anonymous classes may seem unwieldy and unclear ▸ Lambda expressions enable you to do this, to treat functionality as method argument, or code as data
  52. LAMBDA EXPRESSION ON ANDROID ▸ Lambda expression ▸ Java 8

    ▸ Android ▸ Java 6, 7 ▸ Retrolambda ▸ Android Studio ▸ Support lambda expression for “shorten display only”
  53. CREATING OBSERVABLES ▸ Observable.just() ▸ Convert an object or a

    set of objects into an Observable that emits that or those objects
  54. RXLIFECYCLE ▸ Helper to handle Android lifecycle ▸ This helper

    automatically determines (based on the lifecycle sequence itself) when the source should stop emitting items ▸ The easy way ▸ extends Rx-Activity or Rx-Fragment family ▸ Observable.bindToLifecycle()
  55. TEXT RECAP: REACTIVEX ON ANDROID ▸ RxJava ▸ Release the

    power of ReactiveX and FRP on Android ▸ RxAndroid ▸ Android Thread controller for RxJava ▸ RxLifecycle ▸ RxJava Helper for complex Activity and Fragment lifecycle
  56. TODAY WE WILL TALK ABOUT.. ▸ Review the Issues and

    Challenges in Android Client App Development ▸ Uncle Bob: Clean Architecture ▸ Everything is a Stream - ReactiveX to the Rescue! ▸ The Most Powerful REST Client Library - Retrofit ▸ Android MVVM Pattern - Data Binding Support Library ▸ The Combined Solution - Demo and Recap
  57. HTTP://SQUARE.GITHUB.IO/RETROFIT/ RETROFIT FEATURES ▸ Most powerful Android Client library ▸

    Don’t need to write a lot of boilerplate codes ▸ Easy and flexible to use ▸ Allow to plugin your modified HTTP client, JSON converter, and etc. ▸ Only need to define the API interface to work
  58. EXAMPLE: GET THE REPO LIST OF AN ORG ON GITHUB

    RETROFIT SUPPORTS RXJAVA ▸ It help you to trigger the RESTful requests and create the Observables
  59. RETROFIT SUPPORTS RXJAVA ▸ Just use the Observable created by

    Retrofit and subscribe the Subscriber to work!
  60. RETROFIT 2.0.0 ▸ Still beta (2.0.0-beta3), but okay to use

    with RxJava Observable ▸ Rewritten, so not compatible with 1.x ▸ Directly use and deeply integrate with OkHttp
  61. TODAY WE WILL TALK ABOUT.. ▸ Review the Issues and

    Challenges in Android Client App Development ▸ Uncle Bob: Clean Architecture ▸ Everything is a Stream - ReactiveX to the Rescue! ▸ The Most Powerful REST Client Library - Retrofit ▸ Android MVVM Pattern - Data Binding Support Library ▸ The Combined Solution - Demo and Recap
  62. TEXT DATA BINDING FEATURES ▸ Data Binding Library automatically generate

    those boilerplate codes ▸ project/app/build/intermediates/classes/debug/ com.example.application/databinding/ MainActivityBinding.java ▸ Two-way binding with Observable objects ▸ Easy to test with ViewModel ▸ Mock test data in ViewModel
  63. TEXT DATA BINDING FEATURES ▸ Expression language ▸ android:visibility="@{age <

    13 ? View.GONE : View.VISIBLE}” ▸ Advanced binding ▸ Support RecyclerView
  64. TEXT DATA BINDING ▸ The real power of data binding

    can be used by giving your data objects the ability to notify when data changes ▸ Observable data objects
  65. OBSERVABLE DATA OBJECTS ▸ Observable objects ▸ extends BaseObservable ▸

    Observable fields ▸ ObservableField<String> ▸ ObservableInt, ObservableLong, … ▸ Observable collections ▸ ObservableArrayMap, ObservableArrayList
  66. TEXT ANDROID MVVM DATA BINDING EXAMPLE ▸ ANDROID DATABINDING: GOODBYE

    PRESENTER, HELLO VIEWMODEL! ▸ https://github.com/Nilzor/mvp-to-mvvm-transition
  67. TODAY WE WILL TALK ABOUT.. ▸ Review the Issues and

    Challenges in Android Client App Development ▸ Uncle Bob: Clean Architecture ▸ Everything is a Stream - ReactiveX to the Rescue! ▸ The Most Powerful REST Client Library - Retrofit ▸ Android MVVM Pattern - Data Binding Support Library ▸ The Combined Solution - Demo and Recap
  68. ANDROID CLIENT APP DEVELOPMENT RECAP: WE HAVE TWO MAJOR PROBLEMS

    COMBINED TOGETHER ▸ Android lifecycle is too complex, especially with async tasks ▸ Android async tasks are hard to write and manage when firing many RESTful requests