Welcome back.
In this video, we've got some slides to explain how different instances of the same ViewModel work.
Before making the change, we can confirm that behaviour.
I'll run the app again.
and filter the logcat
on tasktimerviewmodel
to make it easier to find things, use control f and search tasktimerviewmodel
That highlights the entries to distinguish them from the app provider entries.
Tap the plus button to add a new task task
Task 9
9th task.
Save the task and we can see a new TaskTimerViewModel instance
created in the logcat.
We can see the entries TaskTimerViewModel created
appearing twice
and each one is accompanied by AppProviderQuery called with
and the URI.
We've already seen the change we need to make in AddEditFragment.
We just need to change this to activity
We've had to use the bangbang operator there, to provide a non nullable activity
As we know from the fragment life cycle the activity can be null at times.
As a result, it is essential that we don't attempt to use the view model any
earlier than onActivityCreated.
A lazy delegate will initialize view model the
first time it is referred to, and the activity is non null by the time
onActivityCreated runs. I'll run the app again
and keep an eye on logcat.
I've still got the filter, to make it easier to see just the bits that we're interested in.
When MainActivityFragment starts,
we get a TaskTimerViewModel instance created,
and the database is queried
I'll edit task 10
and change the word first back to the digit 1st
when I tap save, we no longer get a new ViewModel instance,
and the database is only requeried after the update.
Okay, that's the end of this video.
We've gone into a lot more detail about ViewModels,
but I think it's important to understand
the things we've covered here, if you're going to use them without getting
strange bugs.
The scope that you use for the view model is important,
especially when using them for multiple fragments.
In this example, and the slides,
I've explained what's going on and why you may want to use the Activity as the
scope, when you have more than one Fragment at the same time.
Our app can now
add, edit and delete the task records.
I'm going to stop this section here but that's not the end of our app.
In the next section we'll use it to have a look
at dialogues. See you in the next section