What is the proper way to launch a coroutine on Android?
I have Coroutines.kt
object Coroutines {
fun main(work: suspend (() -> Unit)) {
CoroutineScope(Dispatchers.Main).launch {
work()
}
}
}
and I use it in my viewmodels by calling Couroutines.main
Last two solutions are fine. CoroutineScope(context: CoroutineContext)
creates an empty Job
if you pass a context without one.
Specifying job + dispatcher
is just more explicit way to build it as in some cases you might want to use a SupervisorJob
instead to prevent entire scope from being canceled when one of child jobs fail.
As for building scopes in Activities
and ViewModels
instead of declaring your own you can use ones built-in into KTX library by importing KTX fragment module:
// add to your apps dependencies
implementation 'androidx.fragment:fragment-ktx:1.2.0-rc02'
Now inside your Activity
s and Fragment
s you can use lifecycleScope
and inside ViewModel
a viewModelScope
which are scopes backed by SupervisorJob + Dispatchers.Main.immediate
and are automatically canceled when their respective lifecycle is destroyed.
For someone just looking for a simple way to launch a Coroutine with an Android Activity without all the bells and whistles, here's a quick and simple way (but you should still look into learning how to use Coroutines correctly, i.e. with ViewModels & CoroutineScope)
- Add androidx.lifecycle to your app-level build.gradle:
implementation "androidx.lifecycle:lifecycle-runtime-ktx:2.4.1"
(check Link above for current version)
- In the Activity, use the Activity-provided LifecycleScope to launch the Coroutine (mostly pseudo-code):
import androidx.lifecycle.lifecycleScope
class YourActivity {
override fun onCreate() {
lifeCycleScope.launch {
// do your Coroutine Stuff here, i.e. call a suspend fun:
coroutineFunction()
}
}
suspend fun coroutineFunction() {
// Use a different CoroutineScope, etc
CoroutineScope(Dispatchers.IO).launch {
// do some long running operation or something
}
}
}