Last active
April 17, 2019 19:33
-
-
Save tuvior/6708aab7fbe53b6d222b77efa4d23183 to your computer and use it in GitHub Desktop.
Kotlin Coroutine resume issue
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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