elizarov
09/13/2017, 7:37 PMrun
function from kotlinx.coroutines
like this:
val btContext = newSingleThreadContext("Bluetooth") // a context with one thread for BT ops
suspend fun readFromBT() = run(btContext) { // convert blocking into non-blocking with run
// do blocking read from bluetooth
result
}
Having defined it, you can use readFromBT
from any coroutine and it is not going to block(!). For example, you can do it from a UI-bound coroutine:
launch(UI) { // launch coroutine using UI dispatcher from kotlinx-coroutines-android
while (true) {
val data = readFromBT()
displayData(data) // you are in UI thread here!!!
}
}