Welcome back. All right.
Did you spot what we did in TaskTimerViewModel
that we didn't do in DurationsViewModel.
We're not observing the changes to the database
and don't update the adapter when the data changes.
The code is almost identical to the code we used in TaskTimerViewModel.
So I'll copy and paste it from there.
Accept the imports then change the function name.
We called it LoadTasks in TaskTimerViewModel,
but it's called LoadData in this class,
that's declared our ContentObserver. Now we have to register it.
We do that in the init block.
Once again, that's very similar to the code in the TaskTimerViewModel class.
We're observing changes to the timings table
rather than the tasks table
so we use the timings contract content URI.
I've also obtained the application reference a bit differently.
Inside the init block,
we still have access to any arguments passed to the constructor
that means we don't have to call get application,
we can use application directly.
I wanted to point that out
but I'd probably use get application throughout the class
as I did in the TaskTimerViewModel.
It's less confusing if all the references to the application object
are obtained in the same way.
But if you see other android view model classes that access
application directly in their init block,
you now know that it's exactly the same object
the get application returns.
The last thing we need to do is stop observing
when our ViewModel is being destroyed.
That's important, failing to do it can result in your app leaking resources.
I'll copy the entire uncleared function
from TaskTimerViewModel and paste it at the end of this class.
That's all the changes we need to make, let's see if it works.
I'll run the app again
and delete all the records before the 15th of May
2019.
This time the display updates as soon as I confirm the change.
Creating observers is a flexible way for your classes to react to changes
in other parts of the system.
Our activities are observing the live data objects
in the ViewModel classes,
and our ViewModels are observing the URIs
that they pass to the on ContentResolver.
We haven't had to create interfaces
to implement CallBack functions
to let the ViewModels know the data has changed.
As long as you remember to unregister your observers to avoid memory leaks,
you'll find observers are very useful.
We'll be using another observer later when we get the reports to update
if the user changes the settings.
But before that,
we've got a small bug in our code,
I'll demonstrate it in the next video. See you there.