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

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:

❤️ Is this article helpful?

Buy me a coffee ☕ or support my work via PayPal to keep this space 🖖 and ad-free.

Do send some 💖 to @d_luaz or share this article.

✨ By Desmond Lua

A dream boy who enjoys making apps, travelling and making youtube videos. Follow me on @d_luaz

👶 Apps I built

Travelopy - discover travel places in Malaysia, Singapore, Taiwan, Japan.