3

背景

我正在尝试使用存储库和用例/交互器实现 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>>
}

问题

在我的示例中,我需要GetFbUserUseCaseGetAllUsersUseCase. 它们都发出加载、错误和结果状态,我想直接委托给 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 流程,有多个选项可以组合和展平多个流程。哪一个最适合我的问题,我将如何实施?

4

1 回答 1

0

我看到combine解决了你的问题。

以下是如何结合这两个流程

firebaseUser.combine(userList).collect { fbuser, userlist -> 
  //combine the results and set the livedata here
  someFunThatSetsLiveData(fbuser, userlist)
}    

每当这些流之一发出新结果时,都会调用 someFunThatSetsLiveData。

于 2020-05-14T22:21:20.050 回答