Start a Project

Android RoomDatabase with ViewModel and Coroutines

Coroutine:

coroutines are light-weight threads. They are launched with launch coroutine builder in a context of some CoroutineScope. A coroutine is a method that executes for a certain period, suspends, and permits other coroutines to run.

Use Cases:

The common use cases for coroutines on Android would be fetching data from the network, parsing large JSON datasets, writing data to a database. Therefore, calling code like this from the main thread can cause the app to pause, stutter, or even freeze. And if you block the main thread for too long, the app may even crash and present an Application Not Responding dialog.

Add dependenceis:

To get started with coroutines on Android you will need to add coroutine and following dependencies.

 

Database Call using coroutines

We have ViewModel with some LiveData objects that the Activity will be able to observe added. Add a coroutine scope to MainViewModel. In Kotlin, all coroutines run inside a CoroutineScope.A scope controls the lifetime of coroutines through its job.

 

 

Exit mobile version