
com.github.insanusmokrassar.AutoPostTelegramBot.utils.extensions.BroadcastChannel.kt Maven / Gradle / Ivy
package com.github.insanusmokrassar.AutoPostTelegramBot.utils.extensions
import kotlinx.coroutines.experimental.*
import kotlinx.coroutines.experimental.channels.*
import java.util.concurrent.TimeUnit
fun BroadcastChannel.subscribeChecking(
throwableHandler: (Throwable) -> Boolean = {
it.printStackTrace()
true
},
by: suspend (T) -> Boolean
): ReceiveChannel {
return openSubscription().apply {
subscribeChecking(
throwableHandler,
by
)
}
}
fun BroadcastChannel.subscribe(
throwableHandler: (Throwable) -> Boolean = {
it.printStackTrace()
true
},
by: suspend (T) -> Unit
): ReceiveChannel {
return openSubscription().apply {
subscribeChecking(throwableHandler) {
by(it)
true
}
}
}
fun ReceiveChannel.subscribeChecking(
throwableHandler: (Throwable) -> Boolean = {
it.printStackTrace()
true
},
by: suspend (T) -> Boolean
) {
val channel = this
launch {
while (isActive && !channel.isClosedForReceive) {
try {
val received = channel.receive()
launch {
try {
if (!by(received)) {
channel.cancel()
}
} catch (e: Throwable) {
if (!throwableHandler(e)) {
channel.cancel()
}
}
}
} catch (e: CancellationException) {
break
}
}
channel.cancel()
}
}
fun ReceiveChannel.subscribe(
throwableHandler: (Throwable) -> Boolean = {
it.printStackTrace()
true
},
by: suspend (T) -> Unit
) {
return subscribeChecking(throwableHandler) {
by(it)
true
}
}
fun BroadcastChannel.debounce(
delay: Long,
timeUnit: TimeUnit = TimeUnit.MILLISECONDS
): BroadcastChannel {
return openSubscription().debounce(
delay,
timeUnit
)
}
fun ReceiveChannel.debounce(
delay: Long,
timeUnit: TimeUnit = TimeUnit.MILLISECONDS
): BroadcastChannel {
return BroadcastChannel(Channel.CONFLATED).also {
outBroadcast ->
var lastReceived: Job? = null
subscribe {
lastReceived ?.cancel()
lastReceived = launch {
delay(delay, timeUnit)
outBroadcast.send(it)
}
}
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy