All Downloads are FREE. Search and download functionalities are using the official Maven repository.

commonMain.remote.coroutines.session.SessionWatcher.kt Maven / Gradle / Ivy

package ch.softappeal.yass2.remote.coroutines.session

import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
import kotlinx.coroutines.withTimeout

/** Launches a new coroutine that closes [session] if [check] throws an exception or doesn't return within [timeoutMillis]. */
public fun  CoroutineScope.watch(
    session: Session,
    intervalMillis: Long = 10_000,
    timeoutMillis: Long = 1000,
    check: suspend () -> Unit,
): Job {
    require(intervalMillis > 0)
    require(timeoutMillis > 0)
    return launch {
        while (isActive) {
            try {
                withTimeout(timeoutMillis) { check() }
            } catch (e: Exception) {
                session.close(e)
                break
            }
            delay(intervalMillis)
        }
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy