Melvin Biamont
12/02/2019, 1:40 PMsuspend
function and lambdas:
Sometimes, I use lambdas in suspend functions, and inside the lambda, I would like to call another suspend function like this:
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:
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.
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?Arjun Achatz
12/02/2019, 2:30 PMtseisel
12/02/2019, 5:38 PMsuspend
functions has been added recently.callback
parameter to a suspend
function ; the whole point of suspend
functions is precisely to avoid callbacks !