androidkotlinkotlin-coroutineskotlin-flow

How to convert the data without collecting the flow?


I'm trying to convert the data I read from a repo class inside a ViewModel like this:

val itemFlow = flow {
    repo.getItemList().collect { itemList ->
        val itemListResult = try {
            Result.Success(itemList)
        } catch (e: Exception) {
            Result.Failure(e)
        }
        emit(itemListResult)
    }
}

My Result class looks like this:

sealed class Result<out T> {
    data class Success<out T>(val data: T) : Result<T>()
    data class Failure(val e: Exception) : Result<Nothing>()
}

And here is how I read the data from Room in the repo class:

override fun getItemList() = itemDao.getItemList()

Is there any way I can transform the itemList into an object of type Result.Success and Result.Failure without collecting the data?


Solution

  • Your implementation of try-catch is incorrect as it will not be able to catch any error from the getItemList method. As long as you don't call terminal operators like collect or launchIn your flow will remain cold. You can try the following:

    val itemFlow = repo.getItemList()
        .map { Result.Success(it) } 
        .catch { e -> Result.Failure(e) }