This codelab is part of the Android Kotlin Fundamentals course. You'll get the most value out of this course if you work through the codelabs in sequence. All the course codelabs are listed on the Android Kotlin Fundamentals codelabs landing page.


One of the top priorities for creating a flawless user experience for your app is to make sure the UI is always responsive and runs smoothly. One way to improve UI performance is to move long-running tasks, such as database operations, into the background.

In this codelab, you implement the user-facing portion of the TrackMySleepQuality app, using Kotlin coroutines to perform database operations away from the main thread.

What you should already know

You should be familiar with:

What you'll learn

What you'll do

In this codelab, you build the view model, coroutines, and data-display portions of the TrackMySleepQuality app.

The app has two screens, represented by fragments, as shown in the figure below.

The first screen, shown on the left, has buttons to start and stop tracking. The screen shows all the user's sleep data. The Clear button permanently deletes all the data that the app has collected for the user.

The second screen, shown on the right, is for selecting a sleep-quality rating. In the app, the rating is represented numerically. For development purposes, the app shows both the face icons and their numerical equivalents.

The user's flow is as follows:

This app uses a simplified architecture, as shown below in the context of the full architecture. The app uses only the following components:

In this task, you use a TextView to display formatted sleep tracking data. (This is not the final interface. You will learn a better way in another codelab.)

You can continue with the TrackMySleepQuality app that you built in the previous codelab or download the starter app for this codelab.

Step 1: Download and run the starter app

  1. Download the TrackMySleepQuality-Coroutines-Starter app from GitHub.
  2. Build and run the app. The app shows the UI for the SleepTrackerFragment fragment, but no data. The buttons do not respond to taps.

Step 2: Inspect the code

The starter code for this codelab is the same as the solution code for the 6.1 Create a Room database codelab.

  1. Open res/layout/activity_main.xml. This layout contains the nav_host_fragment fragment. Also, notice the <merge> tag.

    The merge tag can be used to eliminate redundant layouts when including layouts, and it's a good idea to use it. An example of a redundant layout would be ConstraintLayout > LinearLayout > TextView, where the system might be able to eliminate the LinearLayout. This kind of optimization can simplify the view hierarchy and improve app performance.
  2. In the navigation folder, open navigation.xml. You can see two fragments and the navigation actions that connect them.
  3. In the layout folder, double-click the sleep tracker fragment to see its XML layout. Notice the following:

The starter app also provides dimensions, colors, and styling for the UI. The app contains a Room database, a DAO, and a SleepNight entity. If you did not complete the preceding codelab, make sure you explore these aspects of the code on your own.

Now that you have a database and a UI, you need to collect data, add the data to the database, and display the data. All this work is done in the view model. Your sleep-tracker view model will handle button clicks, interact with the database via the DAO, and provide data to the UI via LiveData. All database operations will have to be run away from the main UI thread, and you'll do that using coroutines.

Step 1: Add SleepTrackerViewModel

  1. In the sleeptracker package, open SleepTrackerViewModel.kt.
  2. Inspect the SleepTrackerViewModel class, which is provided for you in the starter app and is also shown below. Note that the class extends AndroidViewModel(). This class is the same as ViewModel, but it takes the application context as a parameter and makes it available as a property. You will need this later.
class SleepTrackerViewModel(
       val database: SleepDatabaseDao,
       application: Application) : AndroidViewModel(application) {

Step 2: Add SleepTrackerViewModelFactory

  1. In the sleeptracker package, open SleepTrackerViewModelFactory.kt.
  2. Examine the code that's provided for you for the factory, which is shown below:
class SleepTrackerViewModelFactory(
       private val dataSource: SleepDatabaseDao,
       private val application: Application) : ViewModelProvider.Factory {
   override fun <T : ViewModel?> create(modelClass: Class<T>): T {
       if (modelClass.isAssignableFrom( {
           return SleepTrackerViewModel(dataSource, application) as T
       throw IllegalArgumentException("Unknown ViewModel class")

Take note of the following:

Step 3: Update SleepTrackerFragment

  1. In the SleepTrackerFragment, get a reference to the application context. Put the reference in onCreateView(), below binding. You need a reference to the app that this fragment is attached to, to pass into the view-model factory provider.

    The requireNotNull Kotlin function throws an IllegalArgumentException if the value is null.
val application = requireNotNull(this.activity).application
  1. You need a reference to your data source via a reference to the DAO. In onCreateView(), before the return, define a dataSource. To get a reference to the DAO of the database, use SleepDatabase.getInstance(application).sleepDatabaseDao.
val dataSource = SleepDatabase.getInstance(application).sleepDatabaseDao
  1. In onCreateView(), before the return, create an instance of the viewModelFactory. You need to pass it dataSource and the application.
val viewModelFactory = SleepTrackerViewModelFactory(dataSource, application)
  1. Now that you have a factory, get a reference to the SleepTrackerViewModel. The parameter refers to the runtime Java class of this object.
val sleepTrackerViewModel =
               this, viewModelFactory).get(
  1. Your finished code should look like this:
// Create an instance of the ViewModel Factory.
val dataSource = SleepDatabase.getInstance(application).sleepDatabaseDao
val viewModelFactory = SleepTrackerViewModelFactory(dataSource, application)

// Get a reference to the ViewModel associated with this fragment.
val sleepTrackerViewModel =
               this, viewModelFactory).get(

Here's the onCreateView() method so far:

override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
                              savedInstanceState: Bundle?): View? {

        // Get a reference to the binding object and inflate the fragment views.
        val binding: FragmentSleepTrackerBinding = DataBindingUtil.inflate(
                inflater, R.layout.fragment_sleep_tracker, container, false)

        val application = requireNotNull(this.activity).application

        val dataSource = SleepDatabase.getInstance(application).sleepDatabaseDao

        val viewModelFactory = SleepTrackerViewModelFactory(dataSource, application)

        val sleepTrackerViewModel =
                        this, viewModelFactory).get(

        return binding.root

Step 4: Add data binding for the view model

With the basic ViewModel in place, you need to finish setting up data binding in the SleepTrackerFragment to connect the ViewModel with the UI.

In the fragment_sleep_tracker.xml layout file:

  1. Inside the <data> block, create a <variable> that references the SleepTrackerViewModel class.
       type="" />

In SleepTrackerFragment:

  1. Set the current activity as the lifecycle owner of the binding. Add this code inside the onCreateView() method, before the return statement:
  1. Assign the sleepTrackerViewModel binding variable to the sleepTrackerViewModel. Put this code inside onCreateView(), below the code that creates the SleepTrackerViewModel:
binding.sleepTrackerViewModel = sleepTrackerViewModel
  1. You will probably see an error, because you have to recreate the binding object. Clean and rebuild the project to get rid of the error.
  2. Finally, as always, make sure your code builds and runs without errors.

In Kotlin, coroutines are the way to handle long-running tasks elegantly and efficiently. Kotlin coroutines let you convert callback-based code to sequential code. Code written sequentially is typically easier to read and can even use language features such as exceptions. In the end, coroutines and callbacks do the same thing: they wait until a result is available from a long-running task and continue execution.

Coroutines have the following properties:

Coroutines are asynchronous.

A coroutine runs independently from the main execution steps of your program. This could be in parallel or on a separate processor. It could also be that while the rest of the app is waiting for input, you sneak in a bit of processing. One of the important aspects of async is that you cannot expect that the result is available, until you explicitly wait for it.

For example, let's say you have a question that requires research, and you ask a colleague to find the answer. They go off and work on it, which is like they're doing the work "asynchronously" and "on a separate thread." You can continue to do other work that doesn't depend on the answer, until your colleague comes back and tells you what the answer is.

Coroutines are non-blocking.

Non-blocking means that a coroutine does not block the main or UI thread. So with coroutines, users always have the smoothest possible experience, because the UI interaction always has priority.

Coroutines use suspend functions to make asynchronous code sequential.

The keyword suspend is Kotlin's way of marking a function, or function type, as being available to coroutines. When a coroutine calls a function marked with suspend, instead of blocking until the function returns like a normal function call, the coroutine suspends execution until the result is ready. Then the coroutine resumes where it left off, with the result.

While the coroutine is suspended and waiting for a result, it unblocks the thread that it's running on. That way, other functions or coroutines can run.

The suspend keyword doesn't specify the thread that the code runs on. A suspend function may run on a background thread, or on the main thread.

To use coroutines in Kotlin, you need three things:

Job: Basically, a job is anything that can be canceled. Every coroutine has a job, and you can use the job to cancel the coroutine. Jobs can be arranged into parent-child hierarchies. Canceling a parent job immediately cancels all the job's children, which is a lot more convenient than canceling each coroutine manually.

Dispatcher: The dispatcher sends off coroutines to run on various threads. For example, Dispatcher.Main runs tasks on the main thread, and Dispatcher.IO offloads blocking I/O tasks to a shared pool of threads.

Scope: A coroutine's scope defines the context in which the coroutine runs. A scope combines information about a coroutine's job and dispatcher. Scopes keep track of coroutines. When you launch a coroutine, it's "in a scope," which means that you've indicated which scope will keep track of the coroutine.

You want the user to be able to interact with the sleep data in the following ways:

These database operations can take a long time, so they should run on a separate thread.

Step 1: Set up coroutines for database operations

When the Start button in the Sleep Tracker app is tapped, you want to call a function in the SleepTrackerViewModel to create a new instance of SleepNight and store the instance in the database.

Tapping any of the buttons triggers a database operation, such as creating or updating a SleepNight. For this reason and others, you use coroutines to implement click handlers for the app's buttons.

  1. Open the app-level build.gradle file and find the dependencies for coroutines. To use coroutines, you need these dependencies, which were added for you.

    The $coroutine_version is defined in the project build.gradle file as coroutine_version = '1.0.0'.
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:$coroutine_version"
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:$coroutine_version"
  1. Open the SleepTrackerViewModel file.
  2. In the body of the class, define viewModelJob and assign it an instance of Job. This viewModelJob allows you to cancel all coroutines started by this view model when the view model is no longer used and is destroyed. This way, you don't end up with coroutines that have nowhere to return to.
private var viewModelJob = Job()
  1. At the end of the body of the class, override onCleared() and cancel all coroutines. When the ViewModel is destroyed, onCleared() is called.
override fun onCleared() {
  1. Right below the definition of viewModelJob, define a uiScope for the coroutines. The scope determines what thread the coroutine will run on, and the scope also needs to know about the job. To get a scope, ask for an instance of CoroutineScope, and pass in a dispatcher and a job.

Using Dispatchers.Main means that coroutines launched in the uiScope will run on the main thread. This is sensible for many coroutines started by a ViewModel, because after these coroutines perform some processing, they result in an update of the UI.

private val uiScope = CoroutineScope(Dispatchers.Main + viewModelJob)
  1. Below the definition of uiScope, define a variable called tonight to hold the current night. Make the variable MutableLiveData, because you need to be able to observe the data and change it.
private var tonight = MutableLiveData<SleepNight?>()
  1. To initialize the tonight variable as soon as possible, create an init block below the definition of tonight and call initializeTonight(). You define initializeTonight() in the next step.
init {
  1. Below the init block, implement initializeTonight(). In the uiScope, launch a coroutine. Inside, get the value for tonight from the database by calling getTonightFromDatabase(), and assign the value to tonight.value. You define getTonightFromDatabase() in the next step.
private fun initializeTonight() {
   uiScope.launch {
       tonight.value = getTonightFromDatabase()
  1. Implement getTonightFromDatabase(). Define it as a private suspend function that returns a nullable SleepNight, if there is no current started SleepNight. This leaves you with an error, because the function has to return something.
private suspend fun getTonightFromDatabase(): SleepNight? { }
  1. Inside the function body of getTonightFromDatabase(), return the result from a coroutine that runs in the Dispatchers.IO context. Use the I/O dispatcher, because getting data from the database is an I/O operation and has nothing to do with the UI.
  return withContext(Dispatchers.IO) {}
  1. Inside the return block, let the coroutine get tonight (the newest night) from the database. If the start and end times are not the same, meaning that the night has already been completed, return null. Otherwise, return the night.
       var night = database.getTonight()
       if (night?.endTimeMilli != night?.startTimeMilli) {
           night = null

Your completed getTonightFromDatabase() suspend function should look like this. There should be no more errors.

private suspend fun getTonightFromDatabase(): SleepNight? {
   return withContext(Dispatchers.IO) {
       var night = database.getTonight()
       if (night?.endTimeMilli != night?.startTimeMilli) {
           night = null

Step 2: Add the click handler for the Start button

Now you can implement onStartTracking(), the click handler for the Start button. You need to create a new SleepNight, insert it into the database, and assign it to tonight. The structure of onStartTracking() is going to look very much like initializeTonight().

  1. Start with the function definition for onStartTracking(). You can put the click handlers above onCleared() in the SleepTrackerViewModel file.
fun onStartTracking() {}
  1. Inside onStartTracking(), launch a coroutine in the uiScope, because you need this result to continue and update the UI.
uiScope.launch {}
  1. Inside the coroutine launch, create a new SleepNight, which captures the current time as the start time.
        val newNight = SleepNight()
  1. Still inside the coroutine launch, call insert() to insert newNight into the database. You will see an error, because you have not defined this insert() suspend function yet. (This is not the DAO function of the same name.)
  1. Also inside the coroutine launch, update tonight.
       tonight.value = getTonightFromDatabase()
  1. Below onStartTracking(), define insert() as a private suspend function that takes a SleepNight as its argument.
private suspend fun insert(night: SleepNight) {}
  1. For the body of insert(), launch a coroutine in the I/O context and insert the night into the database by calling insert() from the DAO.
   withContext(Dispatchers.IO) {
  1. In the fragment_sleep_tracker.xml layout file, add the click handler for onStartTracking() to the start_button using the magic of data binding that you set up earlier. The @{() -> function notation creates a lambda function that takes no arguments and calls the click handler in the sleepTrackerViewModel.
android:onClick="@{() -> sleepTrackerViewModel.onStartTracking()}"
  1. Build and run your app. Tap the Start button. This action creates data, but you cannot see anything yet. You fix that next.
fun someWorkNeedsToBeDone {
   uiScope.launch {



suspend fun suspendFunction() {
   withContext(Dispatchers.IO) {

Step 3: Display the data

In the SleepTrackerViewModel, the nights variable references LiveData because getAllNights() in the DAO returns LiveData.

It is a Room feature that every time the data in the database changes, the LiveData nights is updated to show the latest data. You never need to explicitly set the LiveData or update it. Room updates the data to match the database.

However, if you display nights in a text view, it will show the object reference. To see the contents of the object, transform the data into a formatted string. Use a Transformation map that's executed every time nights receives new data from the database.

  1. Open the Util.kt file and uncomment the code for the definition of formatNights()and the associated import statements. To uncomment code in Android Studio, select all the code marked with // and press Cmd+/ or Control+/.
  2. Notice that formatNights() returns a type Spanned, which is an HTML-formatted string.
  3. Open strings.xml. Notice the use of CDATA to format the string resources for displaying the sleep data.
  4. Open SleepTrackerViewModel. In the SleepTrackerViewModel class, below the definition of uiScope, define a variable called nights. Get all the nights from the database and assign them to the nights variable.
private val nights = database.getAllNights()
  1. Right below the definition of nights, add code to transform nights into a nightsString. Use the formatNights() function from Util.kt.

    Pass nights into the map() function from the Transformations class. To get access to your string resources, define the mapping function as calling formatNights(). Supply nights and a Resources object.
val nightsString = { nights ->
   formatNights(nights, application.resources)
  1. Open the fragment_sleep_tracker.xml layout file. In the TextView, in the android:text property, you can now replace the resource string with a reference to nightsString.
  1. Rebuild your code and run the app. All your sleep data with start times should display now.
  2. Tap the Start button a few more times, and you see more data.

In the next step, you enable functionality for the Stop button.

Step 4: Add the click handler for the Stop button

Using the same pattern as in the previous step, implement the click handler for the Stop button in SleepTrackerViewModel.

  1. Add onStopTracking() to the ViewModel. Launch a coroutine in the uiScope. If the end time hasn't been set yet, set the endTimeMilli to the current system time and call update() with the night data.

    In Kotlin, the return@label syntax specifies the function from which this statement returns, among several nested functions.
fun onStopTracking() {
   uiScope.launch {
       val oldNight = tonight.value ?: return@launch
       oldNight.endTimeMilli = System.currentTimeMillis()
  1. Implement update() using the same pattern as you used to implement insert().
private suspend fun update(night: SleepNight) {
   withContext(Dispatchers.IO) {
  1. To connect the click handler to the UI, open the fragment_sleep_tracker.xml layout file and add the click handler to the stop_button.
android:onClick="@{() -> sleepTrackerViewModel.onStopTracking()}"
  1. Build and run your app.
  2. Tap Start, then tap Stop. You see the start time, end time, sleep quality with no value, and time slept.

Step 5: Add the click handler for the Clear button

  1. Similarly, implement onClear() and clear().
fun onClear() {
   uiScope.launch {
       tonight.value = null

suspend fun clear() {
   withContext(Dispatchers.IO) {
  1. To connect the click handler to the UI, open fragment_sleep_tracker.xml and add the click handler to the clear_button.
android:onClick="@{() -> sleepTrackerViewModel.onClear()}"
  1. Build and run your app.
  2. Tap Clear to get rid of all the data. Then tap Start and Stop to make new data.

Android Studio project: TrackMySleepQualityCoroutines

To launch a coroutine, you need a job, a dispatcher, and a scope:

To implement click handlers that trigger database operations, follow this pattern:

  1. Launch a coroutine that runs on the main or UI thread, because the result affects the UI.
  2. Call a suspend function to do the long-running work, so that you don't block the UI thread while waiting for the result.
  3. The long-running work has nothing to do with the UI, so switch to the I/O context. That way, the work can run in a thread pool that's optimized and set aside for these kinds of operations.
  4. Then call the database function to do the work.

Use a Transformations map to create a string from a LiveData object every time the object changes.

Udacity course:

Android Developer Documentation:

Other documentation and articles:

This section lists possible homework assignments for students who are working through this codelab as part of a course led by an instructor. It's up to the instructor to do the following:

Instructors can use these suggestions as little or as much as they want, and should feel free to assign any other homework they feel is appropriate.

If you're working through this codelab on your own, feel free to use these homework assignments to test your knowledge.

Answer these questions

Question 1

Which of the following are advantages of coroutines:

Question 2

What is a suspend function?

Question 3

What is the difference between blocking and suspending a thread? Mark all that are true.

Start to the next lesson: 6.3 Use LiveData to control button states

For links to other codelabs in this course, see the Android Kotlin Fundamentals codelabs landing page.