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

Kirill Prybylsky

04/13/2020, 10:32 AM
Hello everyone, is it a bad practice to expose flow inner channel like this?
Copy code
fun scan() = callbackFlow<Device> {
    deviceChannel = channel
    hardwareChecker.scanDevices()
}
The goal is to offer from multiple places data to the same flow.
b

bezrukov

04/13/2020, 10:56 AM
If you call
scan()
multiple times - only last subscription will receive updates
k

Kirill Prybylsky

04/13/2020, 10:57 AM
@bezrukov that absolutelly fine
@bezrukov by the way, there maybe be a lot of forever suspended channels, will be created🤔
d

Dominaezzz

04/13/2020, 1:10 PM
Unless the scandevices method suspends, all the channels will be closed immediately. Actually an error will be thrown since you don't call awaitClose.
💪 1
☝️ 1
z

Zach Klippenstein (he/him) [MOD]

04/13/2020, 5:26 PM
I think this is probably dangerous – like Kirill said, a new channel is going to get created every time someone collects this Flow, and they’re never going to be cleaned up. If you want to just launch a single job and publish the scan results as a Flow, you could create a channel yourself and use
receiveAsFlow
to turn it into a flow. However this will just round-robin the results to each collector, which is also probably not what you want. You probably want to create a
BroadcastChannel
to send results on and use
asFlow()
to expose it to your consumers.
❤️ 1
3 Views