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

NSC AD 340 5210 - Week 8

NSC AD 340 5210 - Week 8

Df78ed2e647f52dadaac996721a6bdfb?s=128

Nate Ebel

June 02, 2020
Tweet

Transcript

  1. Week 8 Lecture ViewBinding, ViewModel and MVVM

  2. What are we building this week? Replacing findViewById() using ViewBinding

    02 Project Demo ViewBinding 01 Saving data across configuration changes ViewModel Scoping 04 Android ViewModel Implementing MVVM using Android ViewModel 03
  3. Project Demo What are we building this week?

  4. Week 8 Project Updates • Refactoring ForecastDetailsFragment • Using ViewBinding

    to replace calls to findViewById() • Using ViewModel to implement MVVM • Saving data across configuration changes using ViewModel scoping
  5. ViewBinding Replacing calls to findViewById()

  6. Generate statically typed view references Removes any need for findViewById()

  7. Access Generated View Properties // inflate layout and get ViewBinding

    reference val binding = FragmentForecastDetailsBinding.inflate(inflater, parent, false) // access null-safe properties to reference you views binding.descriptionText.text = viewState.description binding.dateText.text = viewState.date binding.forecastIcon.load(viewState.iconUrl)
  8. Enable ViewBinding // app/build.gradle android { … viewBinding { enabled

    = true } }
  9. ViewModel Separating business logic from UI presentation

  10. “The ViewModel class is designed to store and manage UI-related

    data in a lifecycle conscious way. The ViewModel class allows data to survive configuration changes such as screen rotations”
  11. • Manage data sources • Format data • Save data

    across configuration change • Expose data to be displayed in the UI Using ViewModel
  12. MVVM Separation of business logic and UI presentation

  13. MVVM VIEW VIEW MODEL MODEL

  14. MVVM FRAGMENT VIEW MODEL REPOSITORIES

  15. ViewModel Scoping Save data across configuration changes

  16. • Avoid creating a new ViewModel in response to configuration

    changes • Reuse existing ViewModels (and data) within different scopes ◦ Fragment ◦ Activity ◦ Navigation Graph ViewModel Scoping
  17. • More responsive apps • Fewer network and database requests

    • Better user experience ViewModel Scoping
  18. Demo