How to use the combined result of Kotlin Flows in a viewmodel from multiple usecases/interactors?

Viewed 2678

Background

I'm trying to implement a MVVM-style clean architecture pattern with repositories and usecases/interactors. I would like to use Kotlin Flows for the usecases/interactors. All of the usecases have the same setup and the result is wrapped in a sealed class.

Response wrapper:

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>()
}

all UseCases/Interactors implement:

interface UseCase<T, Params> {
    fun execute(params: Params? = null) : Flow<Response<T>>
}

Problem

In my example I need to use the result of a class GetFbUserUseCase inside the result of GetAllUsersUseCase. Both of them emit a Loading, Error and Result state which i would like to delegate to the UI directly.

Example Code

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
                    }
                }
            }
        }
    }
}

Question:

according to: Kotlin flows, There are multiple options to compose and flatten multiple flows. Which one would best suit my Problem and how would I implement this?

1 Answers

I see combine solves your problem.

Here is how to combine these two flows

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

Whenever one of these flows emit new result, the someFunThatSetsLiveData will be called.

Related