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

Your First MVVM with RxJava in Android

Your First MVVM with RxJava in Android

Demonstrate how to use RxJava to implement MVVM pattern in Android

Elvis Lin

March 20, 2017
Tweet

More Decks by Elvis Lin

Other Decks in Programming

Transcript

  1. • View 向 ViewModel 註冊 • ViewModel 不主動更更新 View •

    ViewModel 不知道 View 的存在 • 實作⽅方式: • Data-binding • RxJava
  2. • 使⽤用 Observer pattern • 提供便便利利的 Thread 控制 • Observer

    建立的⽅方式 • Observer.create() • Observer.just() • ……
  3. 建立⼀一個 ViewModel public class SearchViewModel { private BehaviorSubject<String> scoreValue; public

    SearchViewModel() { scoreValue = BehaviorSubject.create(); } public void searchScore(final String userName) { // do something } public Observable<String> getScoreValueObservable() { return scoreValue; } }
  4. 在 View 中對 ViewModel 註冊 public class SearchScoreActivity extends AppCompatActivity

    { @Override protected void onCreate(Bundle savedInstanceState) { searchViewModel = new SearchViewModel(); } @Override protected void onResume() { searchViewModel.getScoreValueObservable(). observeOn(AndroidSchedulers.mainThread()). subscribe(new Observer<String>() { @Override public void onNext(String value) { updateScoreView(value); } }); } }
  5. 結論 • 關注點分離(Separation of Concerns ) • MVVM 讓 View

    跟 ViewModel 單向/雙向綁定 • View 只負責資料的顯⽰示跟UI事件傳遞 • View 根據 ViewModel 的變化,更更新⾃自⼰己的畫⾯面 • ViewModel 不知道 View 的存在
  6. Contact Info Elvis Lin • Github: 
 https://github.com/elvismetaphor • Blog:

    http://article.elvismetaphor.me • Slides: https://speakerdeck.com/ elvismetaphor
  7. 補充資料 (1/2) • RxJava 2.0 介紹 @Kros
 https://www.slideshare.net/ssuser72c3b0/ rxjava-20 •

    MVP in Practice @洪彥斌
 https://www.slideshare.net/ssuser8674c1/ mvp-in-practice
  8. 補充資料 (2/2) • Introduction to MV(Whatever) in Android
 https://speakerdeck.com/elvismetaphor/ introduction-to-mv-whatever-in-android

    • 使⽤用 Data binding 實作 MVVM 模式
 https://speakerdeck.com/elvismetaphor/ introduction-to-mv-whatever-in-android