bryonnicoson
2/17/2018 - 2:40 PM

Building Coroutines

building coroutines calling suspend functions

@file:Suppress("unused")

import kotlinx.coroutines.experimental.*
import kotlin.coroutines.experimental.suspendCoroutine

fun getStringAsync(): Deferred<String> {
  return async(CommonPool) {
    //simulate something long running
    delay(2000)
    return@async "I'm deferred string"
  }
}

fun callGetStringAsync() {
  launch(Unconfined) {
    println("Calling async operation")
    val deferredString: Deferred<String> = getStringAsync()
    prinln("Waiting for completion")
    val value = deferredString.await() //suspension point
    println("Async operation complete, received value: $value")
  }
}

suspend fun AnsyncOperation.asyncExecute(): String {
  return suspendCoroutine { continuation ->
    this.execute(object: Callback<String>{
      override fun onResult(result: String) {
        continuation.resume(result)
      }
      
      override fun onError(fail: Exception) {
        continuation.resumeWithException(fail)
      }
    })
  }
}




@file:Suppress("unused", "UNUSED_VARIABLE")

suspend fun ansycString(): String {
  delay(1000)
  return "Coroutine"
}

fun callCoroutine() {
  // can't call a suspend function without suspend keyword
  val foo = asyncString()
}

fun callCoroutineAsync() {
  val job: Job = launch(Swing) {
    println("Entered suspendable function, calling async operation")
    val value = asyncString()
    println("Async operation done, got value: $value")
  }
  
  lauch(Unconfined) {
    // continuations are resumed on whatever thread was used for suspending function
  }
  
  launch(Unconfined) {
    // uses cpu bound thread pool for executing tasks
  }
  
  runBlocking {
    // blocks the current thread until the coroutine completes
  }
}