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

mertsimsek

12/23/2019, 11:46 AM
Hi, I am playing with the Flow to download files. I want to start a coroutine and return channel immediately. But channel returned from the ViewModel when startDownloadSendChannel() completes. I hope I could explain.
a

Adam Powell

12/23/2019, 4:05 PM
Try to break down the problem into more composable pieces. Right now you're thinking in channels and channel management, but you don't have to do this with flows.
A flow is a factory for subscriptions. It only does work when it's collected, and may be collected multiple times, creating independent work streams for each collector.
When you write a function that returns a Flow, that function should do no work of its own, it should only construct the Flow so that the Flow knows how to do the work when a caller collects it.
👍 1
Right now your
DownloadController.download
method is doing a lot of work of its own - it is itself a
suspend
function, it's performing
launch
operations that create child jobs of the
withContext
block's scope and don't permit the
withContext
block to return until those launched jobs are complete
2 Views