Rex Iceberg
Rex Iceberg

Reputation: 21

how to use liveData coroutine block

how to use liveData coroutine block

in offical doc

https://developer.android.google.cn/topic/libraries/architecture/coroutines#livedata

now can use livedata with coroutine in liveData block

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

when i try to use like this

fun onLogin(v: View) {
    liveData(context = Dispatchers.IO) {
        val reqLogin = ReqLogin(account = account.value?:"", password = MD5(password.value?:""))
        val data = HttpManager.service(MobileApi::class.java).loginSuspend(reqLogin)
        emit(data.data!!)
    }
}

codes in block not executed

search and found that liveData block always use for assignment

https://medium.com/androiddevelopers/viewmodels-and-livedata-patterns-antipatterns-21efaef74a54

if want to refresh the livedata value, can use Transformations like

LiveData<Repo> repo = Transformations.switchMap(repoIdLiveData, repoId -> {
    if (repoId.isEmpty()) {
        return AbsentLiveData.create();
    }
    return repository.loadRepo(repoId);
});

but how can i use it when 1. activity onResume and refresh the data from server 2. some click event trigger the request and get some new data to show

in my login scenes, use viewModelScope seems more useful

fun onLogin(v: View) {
    val reqLogin = ReqLogin(account = account.value ?: "", password = MD5(password.value ?: ""))
    viewModelScope.launch {
        val data = withContext(Dispatchers.IO) {
            HttpManager.service(MobileApi::class.java).loginSuspend(reqLogin)
        }
        _userInfo.value = data.data!!
        _isLogin.value = true
    }
}

Upvotes: 2

Views: 212

Answers (1)

ysfcyln
ysfcyln

Reputation: 3115

    fun onLogin(v: View) {
    liveData(context = Dispatchers.IO) {
        val reqLogin = ReqLogin(account = account.value?:"", password = MD5(password.value?:""))
        val data = HttpManager.service(MobileApi::class.java).loginSuspend(reqLogin)
        emit(data.data!!)
    }
}

Code block is not executed because the documentation says that

The code block starts executing when LiveData becomes active and is automatically canceled after a configurable timeout when the LiveData becomes inactive.

You should make it active by observing it.

Upvotes: 3

Related Questions