2018-01-04 19:52:25 +01:00
|
|
|
package jp.juggler.subwaytooter.util
|
|
|
|
|
2023-01-15 08:51:13 +01:00
|
|
|
import jp.juggler.util.coroutine.AppDispatchers.withTimeoutSafe
|
2023-01-13 13:22:25 +01:00
|
|
|
import jp.juggler.util.coroutine.launchDefault
|
2021-05-27 04:15:59 +02:00
|
|
|
import kotlinx.coroutines.Job
|
|
|
|
import kotlinx.coroutines.TimeoutCancellationException
|
2020-12-08 21:24:42 +01:00
|
|
|
import kotlinx.coroutines.channels.Channel
|
|
|
|
|
|
|
|
abstract class WorkerBase(
|
2023-01-13 13:22:25 +01:00
|
|
|
private val waiter: Channel<Unit> = Channel(capacity = Channel.CONFLATED),
|
2020-12-08 21:24:42 +01:00
|
|
|
) {
|
|
|
|
|
2021-05-27 04:15:59 +02:00
|
|
|
private val suspendJob: Job
|
2020-12-08 21:24:42 +01:00
|
|
|
|
2021-05-27 04:15:59 +02:00
|
|
|
abstract fun cancel()
|
2020-12-08 21:24:42 +01:00
|
|
|
|
2021-05-27 04:15:59 +02:00
|
|
|
abstract suspend fun run()
|
2020-12-08 21:24:42 +01:00
|
|
|
|
2021-05-27 04:15:59 +02:00
|
|
|
suspend fun waitEx(ms: Long) = try {
|
2023-01-15 08:51:13 +01:00
|
|
|
withTimeoutSafe(ms) { waiter.receive() }
|
2021-06-20 15:12:25 +02:00
|
|
|
} catch (ignored: TimeoutCancellationException) {
|
2021-05-27 04:15:59 +02:00
|
|
|
null
|
|
|
|
}
|
2020-12-08 21:24:42 +01:00
|
|
|
|
2021-05-27 04:15:59 +02:00
|
|
|
fun notifyEx() = waiter.trySend(Unit)
|
2020-12-08 21:24:42 +01:00
|
|
|
|
2021-05-27 04:15:59 +02:00
|
|
|
val isAlive: Boolean
|
|
|
|
get() = suspendJob.isActive
|
|
|
|
|
|
|
|
init {
|
|
|
|
suspendJob = launchDefault { run() }
|
|
|
|
}
|
2018-01-04 19:52:25 +01:00
|
|
|
}
|