I am trying to create a polling mechanism with kotlin coroutines using sharedFlow
and want to stop when there are no subscribers and active when there is at least one subscriber. My question is, is sharedFlow
the right choice in this scenario or should I use channel
. I tried using channelFlow
but I am unaware how to close the channel (not cancel
the job) outside the block body. Can someone help? Here's the snippet.
fun poll(id: String) = channelFlow {
while (!isClosedForSend) {
try {
send(repository.getDetails(id))
delay(MIN_REFRESH_TIME_MS)
} catch (throwable: Throwable) {
Timber.e("error -> ${throwable.message}")
}
invokeOnClose { Timber.e("channel flow closed.") }
}
}