https://kotlinlang.org logo
#coroutines
Title
# coroutines
p

Pablo

08/20/2020, 3:24 PM
Hello I'm using the new version of Room and I'd like to start using
Flow
so what I want to do is change the
List<Animals>
to a
Flow<List<Animals>>
but then, I'm losing the mappers on my
use-case
and on my
presentation
? Is there any way to keep mapping the values from the
data
layer? I mean, my dao now returns a
Flow<List<Animals>>
do I have to change also the repository return to be a
Flow<List<Animals>>
? I had a return
List<AnimalsMappedToDomain>
, but now how can I do that mapper? What would be the flow from repository to presentation using the mappers?
b

bezrukov

08/20/2020, 3:29 PM
just use flow.map:
Copy code
fun animalFlow(): Flow<List<AnimalsMappedToDomain> = dao.animals.map { animals ->
   animals.map { animal ->
      animal.mapToDomain()
   }
}
p

Pablo

08/20/2020, 3:35 PM
Yes, I found this way to do it, the problem comes when I'm on the use-case didn't mention that, that the return is an
Either<Exception,List<AnimalsMappedtoDomain>>
Got me? I mean before I was using this
Either
and then on my
ViewModel
I was using the fold to get the
Left
and
Right
now that I'm changing to
Flow
don't know how to tract this
b

bezrukov

08/20/2020, 3:48 PM
what kind of error do you expect here? typically queries that return List doesn't produce errors (except the cases when your DB is corrupted for example, but handling such exceptions in each query is a bad practice IMO).
p

Pablo

08/20/2020, 3:51 PM
Well I've created like different types of layout like for emptyList NetworkConnection, so from Repository I throw these exceptions and then on domain I convert these Either the exception or the list to an Either so on my ViewModel I can show the list or other layout
b

bezrukov

08/20/2020, 3:52 PM
But if you want to return Flow<Either<Exception, List<Animal>>, you can write top-level fun that converts
Flow<T>
to
Flow<Either<Exception, T>>
Copy code
fun Flow<T>.handleErrors() = flow {
   try {
       collect {
          emit( // either with element)
       }
   } catch (e: Exception) { 
       emit(// either with error)
   }
}
Another option is to expose
Flow<List<Animal...>>
and in VM use
.catch
operator
p

Pablo

08/20/2020, 4:03 PM
So on my domain can I still use this Either<Exception, List<T>>? Or do I have to change it
?
6 Views