'Using Coroutines with Third party library that's using callback handlers

Here is a breakdown of how the current third party SDK implementation works.

class Handler(val context: Context) {


    val device = Controller.getInstance(context,Listener())

    fun connectBT(BTDevice:BluetoothDevice){
        device.connectBT(BTDevice)
    }


}

and then the Listener implementation

class Listener: BBDeviceController.BBDeviceControllerListener{
    override fun onBTConnected(device: BluetoothDevice?) {
        println("Device Connected")
        // Send back to function that device is connect
    }
}

This is a straightforward example, but the idea is, when you press a button it will call connectBT() and then contain the result like so:

val handler = Handler(this)
val res = handler.connectBT(btDevice)

I know you can use suspendCoroutine on the function handler.connectBT() however the issue is how do I get the listeners result from the SDK to return back to the main function that called it?



Solution 1:[1]

When using suspendCoroutine, you need to call resume/resumeWithException/etc on the continuation object. You can store/pass this object anywhere, for example to your listener:

class Handler(val context: Context) {
    val listener = Listener()
    val device = Controller.getInstance(context, listener)

    suspend fun connectBT(BTDevice:BluetoothDevice){
        suspendCoroutine<Unit> { continuation ->
            listener.continuation = continuation
            device.connectBT(BTDevice)
        }
    }
}

class Listener: BBDeviceController.BBDeviceControllerListener{
    var continuation: Continuation<Unit>? = null
    
    override fun onBTConnected(device: BluetoothDevice?) {
        println("Device Connected")
        if (continuation != null) {
            continuation?.resume(Unit)
            continuation = null
        }
    }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Pylyp Dukhov