Good day, everyone. Welcome back.
We've changed our coroutines to use the new ViewModelScope.
Let's see if it works.
Run the app and make sure your logcat's visible.
I'll filter the logcat on ViewModelProvider
and position the emulator over towards the right
so that we can see the logcat entries.
Make sure the regex box is ticked, otherwise the filter won't work.
Remember that we get the process ID
followed by the thread ID after the time for each logcat entry.
You should see the entries from app provider
running on a separate thread.
The retrieved timing entries run on the main thread.
That's the first few entries from app provider in my logcat.
We did that deliberately.
The timing has to be retrieved before the UI is shown
to prevent the user from timing a new task
before we've retrieved the existing one.
The last three from app provider are on a different thread.
I'll edit a task and change its sort order.
When I tap save, the database is updated on another thread.
We also see the data being re-queried again on the background thread.
Of course, you'll want to perform a thorough test of the app.
You should test adding a new task, deleting a task and timing tasks.
You'll also want to make sure the reports are loading data on a background thread.
I won't spend time doing that in this video,
but I didn't want to give the impression that this is all the testing you have to do.
All right. Let's get back to the code and have a look at the SaveTask function
in TaskTimerViewModel.
Whenever we've launched a coroutine using ViewModelScope,
we're passing Dispatchers.IO.
We can see that on line 95 and line 105.
The default dispatcher when using ViewModelScope
is dispatchers.main.
That means our co-routine will run on the main UI thread.
If we don't specify dispatchers.io.
That's a sensible default
because Google don't know what we'll be doing in our coroutines
using dispatchers.main is suitable for a co-routine
that performs light work.
You can find a table that briefly describes the uses for the three dispatchers
in a blog post by Sean McQuillan
Google's android developer advocate.
I'll switch to that blog in my browser.
The table is about two thirds of the way down.
For database work we should use Dispatchers.IO,
which is what we're doing. In the next video,
we'll look at what happens if we just let ViewModelScope users default
and leave the coroutine on the main thread. I'll see you there.