简体   繁体   English

Kotlin 创建自定义协程

[英]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.为简单起见,假设我有一个class A尝试connect() ,并且仅在A内部的class B连接后才连接。

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.我想将classB.connect()设为协程,并使其暂停,因此只有在完成后, val isConnected = classB.isConnected的行才会执行并且值会被正确设置。

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.如果我要使用 java 和回调,我只需将回调传递给classB.connect()方法,并在此回调中设置class A.isConnected值。

is it possible with kotlin coroutines? kotlin 协程可以吗? Thanks谢谢

Convert callback to suspend function using suspendCoroutine .使用 suspendCoroutine 将回调转换为挂起function The function below returns true when the connection succeeds:连接成功时,下面的 function 返回true

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 中connect class A应分别suspend

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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