Hello, I’ve a question about `suspend` function an...
# announcements
m
Hello, I’ve a question about
suspend
function and lambdas: Sometimes, I use lambdas in suspend functions, and inside the lambda, I would like to call another suspend function like this:
Copy code
class A(
   private val b: B,
   private val c: C
){
   suspend fun doSuspendSomething() {
      b.doSomethingElse {
         c.doAnotherThing() //Doesn't work because lambda is not suspend
      }
   }
}

interface B{
   suspend fun doSomethingElse(callback: ()-> Unit)
}

class BImpl: B{
   suspend fun doSomethingElse(callback: ()-> Unit){
      callback()
   }
}

class C {
   suspend fun doAnotherThing() {
      println("I do something very different.")
   }
}
So, my problem is the following: If I simply do:
Copy code
interface B{
   suspend fun doSomethingElse(callback: suspend ()-> Unit)
}
It won’t work in Unit tests using Mockito (I think it’s because in Java, it add a parameter
continuation
). So, another solution would be to use an inline function like this.
Copy code
interface B{
   suspend inline fun doSomethingElse(callback: ()-> Unit)
}
But, it doesn’t work, we can’t inline a virtual function. Does someone have a solution here?
a
Sounds like things with inner suspend functions should be modelled using with(context) instead of making them suspending ? If that's possible for you
t
What version of Mockito are you using ? Support for mocking
suspend
functions has been added recently.
But, I don't understand why you need to pass a
callback
parameter to a
suspend
function ; the whole point of
suspend
functions is precisely to avoid callbacks !