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

bitkid

12/11/2020, 7:55 PM
hi! how can i create a flow where the emitting part runs in a different thread / coroutine context ? assume i have an class which has a method getRemoteService() : Flow<Result>. when calling that method i want the method to immediately start consuming the web service so when i call flow.collect{} it is either already finished or still in the process of fetching. somehow with the flow builders i haven't found a way to do that. should i use in that case a channel directly?
g

Guillermo Alcantara

12/11/2020, 7:58 PM
z

Zach Klippenstein (he/him) [MOD]

12/11/2020, 8:33 PM
You could use a regular flow to actually perform the request, but then in your method use the
shareIn
operator to subscribe eagerly.
b

bitkid

12/11/2020, 8:58 PM
hmm the docs of shareIn says its for multiple consumers. also, somehow code where i use shareIn wont compile .. weird. idea thinks the method is there but the compiler says "Kotlin: Unresolved reference: shareIn" i wrote a mini example here https://github.com/bitkid/ksparql/blob/main/src/test/kotlin/com/bitkid/ksparql/TestClient.kt when the flow is collected it starts reading the bytereadchannel .. not sure how i can start reading directly
z

Zach Klippenstein (he/him) [MOD]

12/12/2020, 1:09 AM
It’s often used for multiple consumers, but you can also use it for this.
b

bitkid

12/12/2020, 11:06 AM
it seems that shareIn does not close the flow even if the underlying flow is done
6 Views