Skip to content

Instantly share code, notes, and snippets.

@delacrixmorgan
Last active February 13, 2019 08:39
Show Gist options
  • Save delacrixmorgan/5cb81dc92ca05478c2ac095dc8f48343 to your computer and use it in GitHub Desktop.
Save delacrixmorgan/5cb81dc92ca05478c2ac095dc8f48343 to your computer and use it in GitHub Desktop.
Kotlin Coroutines Callback

Kotlin Coroutines Callback

interface CallbackListener<T> {
  fun onComplete(result: T)
  fun onException(e: Exception?)
}

suspend fun <T> awaitCallback(block: (CallbackListener<T>) -> Unit): T =
  suspendCancellableCoroutine { cont ->
     block(object : CallbackListener<T> {
       override fun onComplete(result: T) = cont.resume(result)
       override fun onException(e: Exception?) {
         e?.let { cont.resumeWithException(it) }
       }
     })                
  }

fun main(){
  runBlocking {
      val task1 = awaitCallback<Int> { getTask1(it) }
      val task2 = GlobalScope.async {
        delay(3000)
        return@async 2
      }
    
      val result = task1 + task2.await()
      print("Expected Result is 4 : $result")
   }
}

fun getTask1(callback: CallbackListener<Int>) {
  Thread.sleep(1000)
  callback.onComplete(2)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment