我收到了 200 代码,我看到正在加载/错误,但无法获得成功状态。
如何在 ViewModel 中将 Flow 转换为 List?
fun loadUsers() = viewModelScope.launch {
_uiState.value = UiState.LOADING
try {
val users = withContext(Dispatchers.IO) { useCase.invoke() }
_uiState.value = UiState.SUCCESS(users) // **i get an error Required:List<UsersModel> Found: Flow<List<UsersModel>>**
} catch (e: Exception) {
_uiState.value = UiState.FAILURE(e.localizedMessage)
}
}
override suspend fun getAllUsers(): Flow<List<UsersModel>> = flow {
val response = randomUserApi.getResults()
if (response.isSuccessful && response.body() != null) {
response.body()?.let {
response.body()!!.results.map {
it.toModel()
}
}
}
}
sealed class UiState {
data class SUCCESS(val users: List<UsersModel>) : UiState()
这里是更正后的用例代码:
override suspend fun getAllUsers():List<UsersModel> {
val response = randomUserApi.getResults()
val responseBody = response.body()
if (response.isSuccessful && responseBody != null) {
return responseBody.results.map { it.toModel() }
}
throw IOException(
"Failed to retrieve user model: " +
response.errorBody().toString()
)
}