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

NSC AD 340 5210 - Week 8

NSC AD 340 5210 - Week 8

Nate Ebel

June 02, 2020
Tweet

More Decks by Nate Ebel

Other Decks in Programming

Transcript

  1. Week 8
    Lecture
    ViewBinding, ViewModel and
    MVVM

    View full-size slide

  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

    View full-size slide

  3. Project Demo
    What are we building
    this week?

    View full-size slide

  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

    View full-size slide

  5. ViewBinding
    Replacing calls to
    findViewById()

    View full-size slide

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

    View full-size slide

  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)

    View full-size slide

  8. Enable ViewBinding
    // app/build.gradle
    android {

    viewBinding {
    enabled = true
    }
    }

    View full-size slide

  9. ViewModel
    Separating business logic from
    UI presentation

    View full-size slide

  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”

    View full-size slide

  11. ● Manage data sources
    ● Format data
    ● Save data across configuration change
    ● Expose data to be displayed in the UI
    Using ViewModel

    View full-size slide

  12. MVVM
    Separation of business logic and UI
    presentation

    View full-size slide

  13. MVVM
    VIEW VIEW MODEL MODEL

    View full-size slide

  14. MVVM
    FRAGMENT VIEW MODEL REPOSITORIES

    View full-size slide

  15. ViewModel
    Scoping
    Save data across
    configuration changes

    View full-size slide

  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

    View full-size slide

  17. ● More responsive apps
    ● Fewer network and database requests
    ● Better user experience
    ViewModel Scoping

    View full-size slide