叶辰哲
叶辰哲

Reputation: 33

What is the diffrent about write or not suspendCoroutine/resume in suspend function

What is the diffrent about below function.

suspend fun doSomething1():Boolean{
  val res = longtimeFunction()
  return res
}
suspend fun doSomething2():Boolean = suspendCoroutine{ continuation->
  val res = longtimeFunction()
  continuation.resume(res)
}

Upvotes: 1

Views: 861

Answers (1)

Marko Topolnik
Marko Topolnik

Reputation: 200168

There is no difference because this is not how you use suspendCoroutine. In order to achieve the suspending, non-blocking behavior, first you need an API that doesn't perform blocking calls and instead has a method that starts an operation and returns immediately, but takes a callback from you that will be notified of the result. For example:

suspend fun doSomething2() = suspendCoroutine<Boolean> { continuation ->
    asyncLongtimeFunction(object: Callback {
        override fun onSuccess(res: Boolean) {
           continuation.resume(res)
        }
    })
}

Upvotes: 4

Related Questions