Sobes.tech
Junior — Senior

Transforming a callback function into a suspend function

livecode

Task condition

The project uses an API that makes a network request. Its getUser method takes an identifier and a callback function. It is required to wrap this asynchronous call in a suspend function so that the result can be obtained in a coroutine without an explicit callback.

//--> the getUser method works asynchronously but we need to get data synchronously in a coroutine
Api().getUser(id) { user ->

}

//answer
suspend fun getUser(id: String): User = suspendCoroutine<User> { continuation ->
    Api().getUser(id) { user ->
        continuation.resume(user)
    }
}