在我的视图模型中,我正在使用类似的东西-
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
,但是我不知道该怎么做?有人可以帮我吗