背景
我正在尝试使用存储库和用例/交互器实现 MVVM 风格的干净架构模式。我想将 Kotlin Flows 用于用例/交互器。所有用例都具有相同的设置,并且结果被包装在一个密封的类中。
响应包装器:
sealed class Response<out T> {
object Loading : Response<Nothing>()
data class Success<T>(val data: T? = null) : Response<T>()
data class Error(val error: ErrorEntity? = null) : Response<Nothing>()
data class Empty(val msg: Int = R.string.empty_string) : Response<Nothing>()
}
所有用例/交互器都实现:
interface UseCase<T, Params> {
fun execute(params: Params? = null) : Flow<Response<T>>
}
问题
在我的示例中,我需要GetFbUserUseCase
在GetAllUsersUseCase
. 它们都发出加载、错误和结果状态,我想直接委托给 UI。
示例代码
class TaskEditViewModel(
private val getCurrentFbUserUseCase: GetFbUserUseCase,
private val getAllUsersUseCase: GetAllUsersUseCase
) : ViewModel() {
private val _pageState = MutableLiveData<Response<*>>()
val pageState: LiveData<Response<*>>
get() = _pageState
fun getUsers() {
viewModelScope.launch {
// get current user ID from GetFbUserUseCase.
val firebaseUser: Flow<Response<FirebaseUser?>> = getCurrentFbUserUseCase.execute()
// get all users from GetAllUsersUseCase.
val userList: Flow<Response<List<User>>> = getAllUsersUseCase.execute()
// somehow combine both results??
merge(firebaseUser, userList).collect { response ->
// delegate the combined Loading, Error states to the UI ?
_pageState.value = response
// only handle the Success state in the viewmodel?
when (response) {
is Response.Success<*> -> {
// get current user ID from GetFbUserUseCase
// apply filtering on the result of `GetAllUsersUseCase` with the result
// from `GetFbUserUseCase` and show different UI accordingly
if (response.data.filterNot { it.userId == currentUser.userId }.isEmpty()) {
// notify liveData to show current user
} else {
// notify liveData to show complete user list
}
}
}
}
}
}
问题:
根据:Kotlin 流程,有多个选项可以组合和展平多个流程。哪一个最适合我的问题,我将如何实施?