Skip to content

Instantly share code, notes, and snippets.

@tuvior
Last active April 17, 2019 19:33
Show Gist options
  • Save tuvior/6708aab7fbe53b6d222b77efa4d23183 to your computer and use it in GitHub Desktop.
Save tuvior/6708aab7fbe53b6d222b77efa4d23183 to your computer and use it in GitHub Desktop.
Kotlin Coroutine resume issue
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.suspendCancellableCoroutine
import kotlinx.coroutines.withTimeoutOrNull
import java.util.concurrent.TimeUnit
import kotlin.concurrent.thread
import kotlin.coroutines.resume
interface Listener<T> {
fun handle(event: T)
}
val listeners = mutableListOf<Listener<String>>()
fun main() {
runBlocking {
thread {
while(true) {
Thread.sleep(5000)
listeners.forEach { it.handle("whatever") }
}
}
val a = waitFor {
true
}
println(a)
}
}
suspend inline fun waitFor(time: Long = Long.MAX_VALUE, unit: TimeUnit = TimeUnit.SECONDS, crossinline predicate: (String) -> Boolean): String? {
return withTimeoutOrNull(unit.toMillis(time)) {
println("withTimeoutOrNull")
suspendCancellableCoroutine<String> { cont ->
println("suspendCancellableCoroutine")
val listener: Listener<String> = object : Listener<String> {
override fun handle(event: String) {
if (predicate(event)) {
println("resuming")
cont.resume(event)
}
}
}
listeners.add(listener)
println("added listener")
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment