Skip to content

Instantly share code, notes, and snippets.

@vishna
Last active June 18, 2019 09:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vishna/e40b212b1352919a1a835f068828d234 to your computer and use it in GitHub Desktop.
Save vishna/e40b212b1352919a1a835f068828d234 to your computer and use it in GitHub Desktop.
Suspended Variable
/**
* 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