r
04/22/2022, 11:25 PMIO
and the transformation of data happens on Default
. I have something like this:
fun someQuery(): Flow<List<SomeItem>> = database.transactionWithResult {
database.someQueries.someItems(someMapper)
.asFlow()
.flowOn(IO)
.mapToList()
.distinctUntilChanged()
.map { someTransformation(it) }
.flowOn(Default)
}
Is the flowOn(IO)
required?. What about this:
...
database.someQueries.someItems(someMapper)
.asFlow()
.mapToList(IO)
.distinctUntilChanged()
.map { someTransformation(it) }
.flowOn(Default)
...
Would that make any difference? From my understanding, mapToList()
will use Default
if we don't pass a context but I want to make sure IO
is used during the DB access and Default
during the transforming the data. Thanks in advance!baxter
04/23/2022, 1:58 AMDefault
and IO
thread are from basically the same thread pool, so a Default
dispatcher thread can be reused for IO
dispatcher.
I don't know SQLDelight all too well, but typically you wouldn't need to use the flowOn()
on a flow from any library, as it should handle using the right dispatcher before you have access to the stream. The mapToList()
seems to already handle this internally, and you are calling to ensure that someTransformation(it)
is also in the Default
dispatcher.
Honestly, I don't believe you need the flowOn(IO)
or any reference to the IO
dispatcher at all, especially if you are ending your flow construction with flowOn(Default)
. By using that, you're essentially stating that everything above the flowOn()
will run in the dispatcher provided (except any part that is handled by an explicit dispatcher). When you collect, that collect will take on the dispatcher of the scope you provide.baxter
04/23/2022, 1:59 AMflowOn(Default)
at the end of your flow setup.r
04/23/2022, 2:00 AMr
04/23/2022, 2:00 AMr
04/23/2022, 2:01 AMIO
in the mapToList(IO)?
baxter
04/23/2022, 2:02 AMDispatcher.Main
, your collect function will be in the main thread.r
04/23/2022, 2:02 AMr
04/23/2022, 2:02 AMbaxter
04/23/2022, 2:03 AMflowOn()
only affects upstream*
*Some exceptionsr
04/23/2022, 2:05 AMmapToList()
gets executed on IO
when using Androidr
04/23/2022, 2:06 AMmapToList
because it seems here is where the access to the DB happensbaxter
04/23/2022, 2:26 AMr
04/23/2022, 2:30 AMbaxter
04/23/2022, 2:38 AMasFlow()
extension function can be collected safely from a main dispatcher. From what I saw, it's emitting results straight from a listener to the query, but not sure what thread that listener is emitting from.r
04/23/2022, 2:40 AMbaxter
04/23/2022, 5:02 AMtrySend()
in the listener just dumps the data into a channel, while the flow waits on the channel to provide data. It then emits on the dispatcher operating on the flow (whether that is from flowOn()
or the dispatcher in the coroutine scope).
Long story short: It doesn't matter what thread the listener emits in.baxter
04/23/2022, 5:03 AMcallbackFlow
works...baxter
04/23/2022, 5:06 AM