0

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?

1 Answer 1

2

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
        }
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for this, I think I was over-engineering it. A follow up question. Can this still work if different functions return different values. For example. After the device is connected. There is a function to getDeviceInfo() And it has a callback that returns a string of data. How would using the coroutines allow for this flow to work?
@Derek you have to manually manage it, e.g. store each value in your listener and resume only when all the data is gathered. Continuation is a pretty simple thing - it can only be resumed only once, because it will resume suspended function execution.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.