Suspend coroutine until condition is true

女生的网名这么多〃 提交于 2019-12-07 02:05:32

Here's how you can implement it:

class ServiceWrapper {
    @Volatile
    private var deferredUntilConnected = CompletableDeferred<Unit>()

    private val service = Service(object : ConnectionCallback {
        override fun onConnected() {
            deferredUntilConnected.complete(Unit)
        }

        override fun onConnectionSuspended() {
            deferredUntilConnected = CompletableDeferred()
        }
    })

    private suspend fun suspendUntilConnected() = deferredUntilConnected.await()

    ...
}

A general note: just because the service got connected at a certain point doesn't guarantee it will still be connected by the time you use it.

You're in a suspended function, why not something like:

while (!service.isConnected()) {
    delay(1000)
}

You can put additional timeout conditions into this statement.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!