Android使用ViewModel作用域启动并进行生命周期转换

时间:2019-11-10 19:11:47

标签: android kotlin mvvm android-livedata kotlin-coroutines

在我的视图模型中,我正在使用类似的东西-

private val viewState = MainViewState()

    fun isUserLoggedIn() = Transformations.map(myUseCase.performUserAction()) {
        when (it) {
            is UserResult.Loading -> viewState.copy(loading = true)
            is UserResult.UserLoggedIn -> viewState.copy(
                loading = false,
                loggedIn = it.loggedIn
            )
            is UserResult.Error -> viewState.copy(loading = false, error = it.error)
            else -> viewState.copy(loading = false)
        }
    }

我的视图模型扩展了BaseView模型,我在其中做了类似的事情-

open class BaseViewModel(private val coroutineCtx: CoroutineContext = Dispatchers.Main) :
    ViewModel(), CoroutineScope {

    private val job = SupervisorJob()

    override val coroutineContext: CoroutineContext
        get() = job + coroutineCtx

    override fun onCleared() {
        super.onCleared()
        coroutineContext.cancel()
    }
}

这有效,但是我对这种方法不满意。我想在viewModelScope.launch的视图模型中使用Transformations.map,但是我不知道该怎么做?有人可以帮我吗

0 个答案:

没有答案