【发布时间】:2021-12-31 01:46:03
【问题描述】:
采取这种方法
override suspend fun login(email: String, password: String): BaseResult<Unit> {
coroutineScope {
try {
fetchMobileConfig()
} catch (e: Exception) {
// Unhandled because it seems like a fire and forget.
}
}
val loginRequest = LoginRequest(
email = email,
password = password
)
return when (val response = loginNetwork.login(loginRequest)) {
is NetworkResponse.Success -> {
coroutineScope {
launch {
getUserData()
}
}
callSomeFinishingFunctionThatIsSuspending()
BaseResult.Ok(Unit)
}
is NetworkResponse.Error.Unauthorised -> {
BaseResult.Error(response.exception)
}
}
}
我遇到了这个方法,想重构一下。我有一些想法,但想看看有没有更好的东西我没有考虑过。它实际上似乎有效,但感觉有点混乱。
从带有 viewModelScope{} 的 ViewModel 调用该方法。
fetchMobileConfig() 和 getUserData() 函数有点奇怪,但它们目前似乎是“一劳永逸”的方法。基本上如果他们失败了,登录应该不会失败。
返回的 BaseResult 用于通知 ViewModel 状态。如果你好奇loginNetwork中login方法是怎么调用的,看起来是这样的:
override suspend fun login(loginRequest: LoginRequest): NetworkResponse<SessionToken> {
return performRequest {
loginService.login(loginRequest)
}
}
我对目前的工作方式感到满意。
在顶部编写此存储库级别函数的更好方法是什么?我对另一种结构持开放态度。
【问题讨论】:
标签: android kotlin kotlin-coroutines