android viewmodel coroutine scope code example

Example: viewmodelscope android

package com.raj.coroutineall

import androidx.lifecycle.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Dispatchers.IO
import kotlinx.coroutines.delay

class ViewModelLiveDataScope: ViewModel() {


    private val _userId: MutableLiveData<Int> = MutableLiveData()
    val user = Transformations
        .switchMap(_userId) { _userId ->
        liveData(viewModelScope.coroutineContext +  IO ) {
            emit("database.loadUserById() / WebAPIcall()")
            delay(1000);
            emit("database.insertAll_into_another_DB()")
        }
    }



    fun setUserId(userId: Int){
        val update = userId
        if (_userId.value == update) {
            return
        }
        _userId.value = update
    }

}
-------------------------- Activity -------------------------------------
lateinit var viewModel: MainActivityViewModelOperation

oncreate(){
.
.
.
.
        //////////////////////  ViewModelLiveDataScope
        viewModel = ViewModelProvider(this).get(ViewModelLiveDataScope::class.java)
        viewModel.user.observe(this, Observer {
            Log.e("Return Value",it.toString())
            tex.text=it.toString()

        })
         viewModel.setUserId(1)
        //////////////////////
.
.
.
}

Tags:

Misc Example