Hey guys, not sure if this is big enough for slack...
# coroutines
n
Hey guys, not sure if this is big enough for slack, how can I run a suspending coroutine inside another suspending coroutine? I have this callback function in my repository
Copy code
override suspend fun saveConfession(text: String): SaveConfessionResponse = suspendCoroutine {cont ->
        val confessionToSave = ConfessionDataModel(text)
        val call = newConfessionService.saveConfession(confessionToSave)
        call.enqueue(object : Callback<SaveConfessionResponse>{
            override fun onResponse(call: Call<SaveConfessionResponse>, response: Response<SaveConfessionResponse>) {
               cont.resume(response.body()!!)
            }

            override fun onFailure(call: Call<SaveConfessionResponse>, t: Throwable) {
                cont.resumeWithException(t)
            }
        })
    }

And I am trying to call it from my useCase object

   suspend fun execute(text: String): Result = suspendCoroutine{ cont->
        try {
            val response = confessionRepository.saveConfession(text)
            when (response.status) {
                200 -> Result.Success(response.id, 200)
                400 -> Result.Error(null)
                500 -> Result.Error(null)
                else -> Result.Error(null)
            }
        } catch (e: Exception) {
            return Result.Error(e)
        }
    }
/ But i cannot call saveConfession outside of coroutine body, can I somehow get the scope that the execute function was called from?
m
Why do you use
suspendCoroutine
? That shouldn’t be there.
n
@Marc Knaup Well if I understood correctly, this is one way on how to solve callbacks, as I cannot return a value from a callback
So I am trying to solve it by suspending it until I get an answer
m
There is no callback in
execute()
🤔
As you never use
cont
to continue the coroutine, the coroutine would hang forever.
In
saveConfession
it makes sense because you use callbacks.
n
How can I call the
saveConfession
then and wait for it to give me a result before returning from the
execute
?
m
Just remove the
suspendCoroutine
and make it a normal
suspend fun
.
n
@Marc Knaup Thank you, thinking about it, makes perfect sense, I am not sure why I got stuck on it for so long
👍 1
m
because that’s the hard part about coroutines. Once you understand the meaning of ‘suspend’ and ‘continuation’, things will get easier