简体   繁体   中英

Kotlin create a custom coroutine

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

Convert callback to suspend function using suspendCoroutine . The function below returns true when the connection succeeds:

class B {
    suspend fun connect(): Boolean = suspendCoroutine { continuation ->
        someObject.connect(object : SomeListenerInterface {
            override fun onSuccess() {
                continuation.resume(true)
            }
        })
    }
}

connect function in class A should be suspend respectively:

class A {
    suspend fun connect() {
        val isConnected = classB.connect()
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM