Slide 1

Slide 1 text

Week 8 Lecture ViewBinding, ViewModel and MVVM

Slide 2

Slide 2 text

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

Slide 3

Slide 3 text

Project Demo What are we building this week?

Slide 4

Slide 4 text

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

Slide 5

Slide 5 text

ViewBinding Replacing calls to findViewById()

Slide 6

Slide 6 text

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

Slide 7

Slide 7 text

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)

Slide 8

Slide 8 text

Enable ViewBinding // app/build.gradle android { … viewBinding { enabled = true } }

Slide 9

Slide 9 text

ViewModel Separating business logic from UI presentation

Slide 10

Slide 10 text

“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”

Slide 11

Slide 11 text

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

Slide 12

Slide 12 text

MVVM Separation of business logic and UI presentation

Slide 13

Slide 13 text

MVVM VIEW VIEW MODEL MODEL

Slide 14

Slide 14 text

MVVM FRAGMENT VIEW MODEL REPOSITORIES

Slide 15

Slide 15 text

ViewModel Scoping Save data across configuration changes

Slide 16

Slide 16 text

● Avoid creating a new ViewModel in response to configuration changes ● Reuse existing ViewModels (and data) within different scopes ○ Fragment ○ Activity ○ Navigation Graph ViewModel Scoping

Slide 17

Slide 17 text

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

Slide 18

Slide 18 text

Demo