Hey guys, I am trying to create a polling mechanis...
# coroutines
o
Hey guys, I am trying to create a polling mechanism which fetches data when at least one Subscriber is active and would stop otherwise, I started with sharedflow but no luck there so I tried to work it with channelflow but the problem is that the
isClosedForSend
flag is still false in case I cancel the job, and there is no other way to close the channelflow that I am aware of. need some help 🙂
Copy code
fun poll(gameId: String, dispatcher: CoroutineDispatcher, ) = channelFlow {
            while (!isClosedForSend) {
                try {
                    send(repository.getDetails(id))
                    delay(MIN_REFRESH_TIME_MS)
                } catch (throwable: Throwable) {
                    Timber.e("Debug: error -> ${throwable.message}")
                }
                invokeOnClose { Timber.e("Debug: channel flow closed.") }
        }
    }
n
Sounds like you want to use the
shareIn
operator with
WhileSubscribed()
o
yes, did try that too using
callbackFlow
shareIn
but still, the problem of how to
stop
polling once there are no terminal operators, or lets say when all terminator operators are canceled. my problem is idk how to stop polling when there are no terminal operators and start it when there is at least one. with the above flow, it still keeps polling since the channel is still open to send
n
shareIn
will cancel the
callbackFlow
and then resubscribe if a new poller starts. Your lambda will be canceled and then completely restarted.
Just realized you are catching the CancellationException. Rethrow if the exception is CancellationException.
Actually you need to ditch the whole try/catch.
It's called exception transparency, if the collector throws, you are supposed to make sure that your lambda throws that same exception. You can log it, but you need to rethrow it.
Cant get the link to the section on my phone 😅 but it's in these docs https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.flow/-flow/index.html