Skip to content

Instantly share code, notes, and snippets.

@juliuscanute
Last active November 30, 2019 21:04
Show Gist options
  • Select an option

  • Save juliuscanute/079811bc2465747879c9f02119d3c0c8 to your computer and use it in GitHub Desktop.

Select an option

Save juliuscanute/079811bc2465747879c9f02119d3c0c8 to your computer and use it in GitHub Desktop.
[Creating your own suspendable API] #kotlin #coroutine
fun executeBackground(action: suspend () -> Unit) {
GlobalScope.launch { action() }
}
fun executeMain(action: suspend () -> Unit) {
GlobalScope.launch(context = Dispatchers.Main) { action() }
}
suspend fun <T : Any> getValue(provider: () -> T): T =
suspendCoroutine { continuation ->
continuation.resumeWith(Result.runCatching { provider() })
}
executeBackground {
val user = getValue { getUserFromNetwork("101") }
executeMain{ println(user) }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment