I am trying to make a coroutine from a method that I have.
to make things simple, let's say I have a class A that I try to connect() and it is connected only after class B that is inside A is connected.
So, I have this code for example, which offcourse doesn't work but it's just to show my use case-
class A {
fun connect() {
classB.connect()
val isConnected = classB.isConnected
}
}
class B {
val isConnected: Boolean = false
fun connect() {
someObject.connect( SomeListenerInterface {
override fun onSuccess() {
isConnected = true
}
})
}
}
I want to make the classB.connect() as a coroutine, and make it suspended, so only when it is done, the line of val isConnected = classB.isConnected would execute and the value would be set properly.
If I would use java and callbacks, I would just pass a callback to the classB.connect() method, and set the class A.isConnected value inside this callback.
is it possible with kotlin coroutines? Thanks
someObject.connectfunction into a suspend function. You can do that usingsuspendCancellableCoroutinebuilder. Now thatsomeObject.connectis suspend, you need to markB.connectassuspend. The last bit required is aCoroutineScopewhich is a bridge between non-coroutine and coroutine based world. Since you haven't provided the exact code and mentioned what it is doing, it's not possible to suggest the coroutine code but what I wrote earlier is the gist of what you need to do.val ack = CompletableDeferred<Boolean>()insideclassBand I will writeack.complete(true)insideclassB.connect()and inclassA.connect()I will just doclassB.await()after theclassB.connect(). what do you think?