Skip to content

Flow.onIdle #4407

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
kunyavskiy opened this issue Apr 7, 2025 · 0 comments
Open

Flow.onIdle #4407

kunyavskiy opened this issue Apr 7, 2025 · 0 comments

Comments

@kunyavskiy
Copy link
Contributor

Use case

I have a flow of data, which is sent to http stream. I want to have some keep-alive pings in this stream, i.e. send en empty event, if there is nothing coming to flow.

So I want to have a stream transformer, which calls a function every time, when nothing is comming long enough.

The Shape of the API

I've implemented it as the following utility function

@OptIn(ExperimentalCoroutinesApi::class)
public fun <T> Flow<T>.onIdle(interval: Duration, block: suspend ProducerScope<T>.() -> Unit) = channelFlow {
    val data = produceIn(this)
    var finished = false
    while (!finished) {
        select {
            data.onReceiveCatching {
                if (it.isSuccess) {
                    send(it.getOrThrow())
                } else {
                    finished = true
                }
            }
            onTimeout(interval) {
                block()
            }
        }
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants