Last active
November 30, 2019 21:04
-
-
Save juliuscanute/079811bc2465747879c9f02119d3c0c8 to your computer and use it in GitHub Desktop.
[Creating your own suspendable API] #kotlin #coroutine
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
| 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() }) | |
| } |
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
| 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