https://kotlinlang.org logo
#coroutines
Title
# coroutines
n

Nikola Milovic

12/09/2020, 3:23 PM
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

Marc Knaup

12/09/2020, 3:24 PM
Why do you use
suspendCoroutine
? That shouldn’t be there.
n

Nikola Milovic

12/09/2020, 3:25 PM
@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

Marc Knaup

12/09/2020, 3:26 PM
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

Nikola Milovic

12/09/2020, 3:28 PM
How can I call the
saveConfession
then and wait for it to give me a result before returning from the
execute
?
m

Marc Knaup

12/09/2020, 3:28 PM
Just remove the
suspendCoroutine
and make it a normal
suspend fun
.
n

Nikola Milovic

12/09/2020, 3:33 PM
@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

myanmarking

12/09/2020, 4:08 PM
because that’s the hard part about coroutines. Once you understand the meaning of ‘suspend’ and ‘continuation’, things will get easier
2 Views