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?
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) }
7
Yes, You can use “map” operator from koltin API to transform the emitted data from the repository into Result type without collecting the flow.
Please try below code
val itemFlow: Flow<Result<List<Item>>> = repo.getItemList()
.map { itemList ->
try {
Result.Success(itemList)
} catch (e: Exception) {
Result.Failure(e)
}
}
You can transform the flow data using the map operator,
which allow converting each emitted itemList
into Result.Success
or Result.Failure
without collecting the flow.
This approach keeps the flow lazy and handles errors during the transformation seamlessly