Android Kotlin Coroutine Scope for Activity, Fragment and ViewModel (Architecture Components)

October 10, 2019

Dependencies

dependencies {
    def lifecycle_extension_version = '2.2.0-beta01'

    // activity, fragment
    implementation "androidx.lifecycle:lifecycle-runtime-ktx:$lifecycle_extension_version"

    // viewmodel
    implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:$lifecycle_extension_version"

    // optional - livedata
    implementation "androidx.lifecycle:lifecycle-livedata-ktx:$lifecycle_extension_version"
}

Activity and Fragment

class CardFragment : Fragment() { // CoroutineScope by MainScope() {
    fun test() {
        // launch in main/ui thread
        // lifecylerOwner.lifecycleScope.launch {  }
        lifecycleScope.launch { // Dispatchers.Main

        }

        // launch in background thread
        lifecycleScope.launch(Dispatchers.Default) {

        }
    }
}

Some new tricks is available

class CardFragment : Fragment() {
    init {
        lifecycleScope.launchWhenStarted {

        }

        lifecycleScope.launch {
            whenStarted {

            }
        }
    }
}

ViewModel

class CardViewModel : ViewModel() {
    init {
        // new trick to launch when ViewModel created
        viewModelScope.launch {

        }
    }

    fun test() {
        viewModelScope.launch {

        }
    }
}

LiveData

Call suspend coroutines within LiveData source

val userLiveData: LiveData<User> = liveData {
    val data = database.loadUser() // loadUser is a suspend function.
    emit(data)
}

instead of

val userLiveData: LiveData<User> = MutableLiveData()

fun loadUser() {
    launch {
        val data = database.loadUser()
        userLiveData.postValue(data)
    }
}

NOTE: I have yet to explore more practical usage of LiveData coroutines

References:

This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.