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

MVVM com RxJava com Kotlin

MVVM com RxJava com Kotlin

Iremos falar sobre a arquitetura MVVM(Model/View/ViewModel) no Android usando RxJava com Kotlin.

B59b1bd643ff429bb27032b05d4f2e23?s=128

Houssan A. Hijazi

December 18, 2017
Tweet

More Decks by Houssan A. Hijazi

Other Decks in Programming

Transcript

  1. MVVM com RxJava em Kotlin no Android

  2. GDGFoz Quem ? • Houssan Ali Hijazi - hussanhijazi@gmail.com •

    Desenvolvedor Android na www.HElabs.com • Organizador GDG Foz do Iguaçu • www.lojasnoparaguai.com.br • www.desaparecidosbr.org • www.hussan.com.br
  3. GDGFoz Kotlin • 2011/JetBrains • 1.0 em Fev. 2016 •

    1.1 em Mar. 2017 • Pinterest, Coursera, Netflix, Uber, Square, Trello e Basecamp • 17/Maio - Google IO 2017
  4. GDGFoz Kotlin • Interoperabilidade • Null Safety • Conciso

  5. GDGFoz Manifesto reativo • Responsivo - Reagir rápido • Resiliente

    - Reagir a falhas • Elástico - Reagir a carga / Autoescalar • Orientado a mensagens - Comunicação assíncrona Fonte: https://www.reactivemanifesto.org/pt-BR
  6. GDGFoz RxJava • RxJava - Reactive Extensions para a JVM

    - uma biblioteca para compor programas assíncronos e baseados em eventos usando sequências observáveis. • Netflix • 1.0.0 em 18 Nov 2014 • 2.0.0 em 28 Out 2016
  7. GDGFoz RxJava Observable Disposable subscribe(Observer<T>) Emite Observer onNext(T) onComplete() onError(Throwable)

    Consome
  8. GDGFoz RxJava • Observable - Emite dados • Observer -

    Consome dados • Disposable • Operators: map, flatmap, filter, last, first etc.. • Schedulers
  9. GDGFoz Código • Robusto • Estável • Testável • Modular

  10. GDGFoz Model/View/Controller Activity IView

  11. GDGFoz Model/View/Presenter Contract

  12. GDGFoz App

  13. GDGFoz Model/View/Presenter // View contract interface RepositoriesContract{ interface View{ fun

    setRepositories(repositories: List<Repository>) } } // Activity/Fragment class RepositoriesActivity : AppCompatActivity(), RepositoriesContract.View { ... // Passing the View to Presenter presenter = RepositoriesPresenter(this) override fun setRepositories(repositories: List<Repository>) { // Setting data to view }
  14. GDGFoz Model/View/Presenter // Presenter contract interface RepositoriesContract { interface Presenter

    { fun getAllRepositories() } } // Passing View to Presenter class RepositoriesPresenter(val view: RepositoriesContract.View): RepositoriesContract.Presenter lateinit var model: RepositoryModel override fun getAllRepositories() { // Call model and set data to View // Can be RxJava var repositories:List<Repository> = model.getAllRepositories() view.setRepositories(repositories) }
  15. GDGFoz Model/View/ViewModel • Microsoft • 2005 • Orientado à eventos

  16. GDGFoz Model/View/ViewModel

  17. GDGFoz MVVM // ViewModel class RepositoriesViewModel(var model: RepositoryDataSource) { ...

    fun getAllRepositories() { // Return an Observable fun getAllRepositories(): Observable<List<Repository>> = model.getAllRepositories() }
  18. GDGFoz MVVM // Activity/Fragment class RepositoriesActivity : AppCompatActivity() { private

    val viewModel: RepositoriesViewModel by lazy { RepositoriesViewModel(RepositoryModel()) } private val mDisposable = CompositeDisposable() ...
  19. GDGFoz MVVM // Activity/Fragment override fun onCreate(savedInstanceState: Bundle?) { ...

    mDisposable.add( viewModel.getAllRepositories() .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe( // onNext this::setRepositories, // onError { error -> Log.d(TAG, "Error: ", error) }, // onComplete { Log.d(TAG, "Completed: ") } ) ) // Activity/Fragment fun setRepositories(repositories: List<Repository>) { // Setting data to view }
  20. GDGFoz Android lifecycle // Activity/Fragment override fun onDestroy() { super.onDestroy()

    mDisposable.dispose() }
  21. GDGFoz MVP/MVVM class Presenter: IPresenter { override fun getAllRepositories() {

    ... view.setRepositories(repositories) } } class ViewModel { fun getAllRepositories(): Observable<List<Repository>> { ... } }
  22. GDGFoz MVVM tests class RepositoriesViewModelTest { @Mock lateinit var model:

    RepositoryDataSource lateinit var viewModel: RepositoriesViewModel … @Before fun setup() { model = mock() viewModel = RepositoriesViewModel(model) }
  23. GDGFoz MVVM tests @Test fun `get repositories emit correct values`()

    { val repositories = listOf(Repository(name = "Test"), Repository(name = "Test2" `when`(model.getAllRepositories()).thenReturn(Observable.just(repositories)) viewModel.getAllRepositories() .test() .assertNoErrors() .assertComplete() .assertValue(repositories) }
  24. GDGFoz Save states // Save override fun onSaveInstanceState(state: Bundle?) {

    super.onSaveInstanceState(state) //Can create Bundle here state.putAll(viewModel.getState()) } // Restore override fun onRestoreInstanceState(bundle: Bundle) { super.onRestoreInstanceState(bundle) viewModel.restoreState(bundle) }
  25. GDGFoz Activity Fragment CustomView CustomView P / VM View

  26. GDGFoz Lógica de UI ? • Tem lógica de UI

    ? • Sim - Presenter/ViewModel (Testes) • Não - View
  27. GDGFoz Qual ? • Classes Android sem lógica ? •

    Pode ser testado (unit test) ? • Suas classes tem uma responsabilidade bem definida ?
  28. GDGFoz Links • http://reactivex.io/ • https://github.com/ReactiveX/RxJava/ • https://kotlinlang.org/ • https://medium.com/upday-devs/android-architecture-patterns-part-3-

    model-view-viewmodel-e7eeee76b73b • https://github.com/googlesamples/android-architecture • https://github.com/hussanhijazi/retrofit-rxjava-databinding/tree/kotlin-mvvm
  29. Obrigado