Last active
June 18, 2019 09:44
-
-
Save vishna/e40b212b1352919a1a835f068828d234 to your computer and use it in GitHub Desktop.
Suspended Variable
This file contains 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
/** | |
* kinda like `lateinit var` but if it's really late it will make you wait rather than crash. | |
*/ | |
class SuspendedVariable<T> { | |
private val callbacks = mutableListOf<((T) -> Unit)>() | |
private var value: T? = null | |
fun set(t: T) { | |
value = t | |
if (t != null) { | |
callbacks.forEach { it(t) } | |
callbacks.clear() | |
} | |
} | |
suspend fun get() : T = suspendCancellableCoroutine { continuation -> | |
value?.let { | |
continuation.resume(it) | |
return@suspendCancellableCoroutine | |
} | |
val callback = { value : T -> | |
continuation.resume(value) | |
} | |
callbacks += callback | |
continuation.invokeOnCancellation { | |
callbacks -= callback | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment