Share
Embed
Expressive (a)synchronous code using coroutines
As everyone knows, long-running operations in Android apps should never be executed on the main thread. With the goal of protecting developers from making mistakes, the Android ecosystem relies heavily on asynchronous APIs that can be found all over the framework and also in many third-party libraries. Although this might do the trick for simple apps and workflows, this becomes a problem as complexity grows in the codebase. In this talk, we'll explore how to leverage coroutines to convert asynchronous APIs into synchronous ones for the sake of expressiveness, readability and developer sanity.
Flávio Faria
February 27, 2020
Transcript
152 slides
-
fun makeAsyncCall() { val asyncApi = AsyncApi() asyncApi.doSomethingAsync { result
-> // do something useful with result } } -
fun makeAsyncCall() { val asyncApi = AsyncApi() asyncApi.doSomethingAsync { result
-> runOnUiThread { // do something useful with result } } } -
Why are APIs designed like this? Answer: to prevent blocking
the main thread (mostly) -
• Getting the user location • Playing media • Managing
Bluetooth devices -
• Getting the user location • Playing media • Managing
Bluetooth devices • Third-party service libraries -
GATT Server (device) Service 1 Characteristic 1 Characteristic 2 Service
2 Characteristic 1 Characteristic 2 Characteristic 3 -
1. Scan for BLE devices 2. Connect to a device
3. Discover services -
1. Scan for BLE devices 2. Connect to a device
3. Discover services 4. Retrieve characteristic value -
private val adapter = BluetoothAdapter.getDefaultAdapter() fun discoverDevice() { adapter.bluetoothLeScanner.startScan(scanCallback) }
private val scanCallback = object : ScanCallback() { } -
private val adapter = BluetoothAdapter.getDefaultAdapter() fun discoverDevice() { adapter.bluetoothLeScanner.startScan(scanCallback) }
private val scanCallback = object : ScanCallback() { override fun onScanResult(callbackType: Int, result: ScanResult) { } } -
private val adapter = BluetoothAdapter.getDefaultAdapter() fun discoverDevice() { adapter.bluetoothLeScanner.startScan(scanCallback) }
private val scanCallback = object : ScanCallback() { override fun onScanResult(callbackType: Int, result: ScanResult) { if (result.device.name == "My Battery-Powered BLE device") { adapter.bluetoothLeScanner.stopScan(this) val gatt = result.device.connectGatt(context, false, gattCallback) } } } -
private val adapter = BluetoothAdapter.getDefaultAdapter() fun discoverDevice() { adapter.bluetoothLeScanner.startScan(scanCallback) }
private val scanCallback = object : ScanCallback() { override fun onScanResult(callbackType: Int, result: ScanResult) { if (result.device.name == "My Battery-Powered BLE device") { adapter.bluetoothLeScanner.stopScan(this) val gatt = result.device.connectGatt(context, false, gattCallback) } } } -
private val gattCallback = object : BluetoothGattCallback() { override fun
onConnectionStateChange(gatt: BluetoothGatt, status: Int, newState: Int) { } } -
private val gattCallback = object : BluetoothGattCallback() { override fun
onConnectionStateChange(gatt: BluetoothGatt, status: Int, newState: Int) { if (status == BluetoothGatt.GATT_SUCCESS && newState == BluetoothGatt.STATE_CONNECTED) { gatt.discoverServices() } } } -
private val gattCallback = object : BluetoothGattCallback() { override fun
onConnectionStateChange(gatt: BluetoothGatt, status: Int, newState: Int) { if (status == BluetoothGatt.GATT_SUCCESS && newState == BluetoothGatt.STATE_CONNECTED) { gatt.discoverServices() } } } -
private val gattCallback = object : BluetoothGattCallback() { override fun
onConnectionStateChange(gatt: BluetoothGatt, status: Int, newState: Int) { if (status == BluetoothGatt.GATT_SUCCESS && newState == BluetoothGatt.STATE_CONNECTED) { gatt.discoverServices() } } } -
private val gattCallback = object : BluetoothGattCallback() { override fun
onConnectionStateChange(gatt: BluetoothGatt, status: Int, newState: Int) {…} } -
private val gattCallback = object : BluetoothGattCallback() { override fun
onConnectionStateChange(gatt: BluetoothGatt, status: Int, newState: Int) {…} override fun onServicesDiscovered(gatt: BluetoothGatt, status: Int) { } } -
private val gattCallback = object : BluetoothGattCallback() { override fun
onConnectionStateChange(gatt: BluetoothGatt, status: Int, newState: Int) {…} override fun onServicesDiscovered(gatt: BluetoothGatt, status: Int) { if (status == BluetoothGatt.GATT_SUCCESS) { gatt.services .find { it.uuid == BATTERY_SERVICE_UUID } ?.characteristics ?.find { it.uuid == BATTERY_CHAR_UUID } ?.let { characteristic -> gatt.readCharacteristic(characteristic) } } } } -
private val gattCallback = object : BluetoothGattCallback() { override fun
onConnectionStateChange(gatt: BluetoothGatt, status: Int, newState: Int) {…} override fun onServicesDiscovered(gatt: BluetoothGatt, status: Int) { if (status == BluetoothGatt.GATT_SUCCESS) { gatt.services .find { it.uuid == BATTERY_SERVICE_UUID } ?.characteristics ?.find { it.uuid == BATTERY_CHAR_UUID } ?.let { characteristic -> gatt.readCharacteristic(characteristic) } } } } -
private val gattCallback = object : BluetoothGattCallback() { override fun
onConnectionStateChange(gatt: BluetoothGatt, status: Int, newState: Int) {…} override fun onServicesDiscovered(gatt: BluetoothGatt, status: Int) { if (status == BluetoothGatt.GATT_SUCCESS) { gatt.services .find { it.uuid == BATTERY_SERVICE_UUID } ?.characteristics ?.find { it.uuid == BATTERY_CHAR_UUID } ?.let { characteristic -> gatt.readCharacteristic(characteristic) } } } } -
private val gattCallback = object : BluetoothGattCallback() { override fun
onConnectionStateChange(gatt: BluetoothGatt, status: Int, newState: Int) {…} override fun onServicesDiscovered(gatt: BluetoothGatt, status: Int) {…} } -
private val gattCallback = object : BluetoothGattCallback() { override fun
onConnectionStateChange(gatt: BluetoothGatt, status: Int, newState: Int) {…} override fun onServicesDiscovered(gatt: BluetoothGatt, status: Int) {…} override fun onCharacteristicRead( gatt: BluetoothGatt, characteristic: BluetoothGattCharacteristic, status: Int ) { } } -
private val gattCallback = object : BluetoothGattCallback() { override fun
onConnectionStateChange(gatt: BluetoothGatt, status: Int, newState: Int) {…} override fun onServicesDiscovered(gatt: BluetoothGatt, status: Int) {…} override fun onCharacteristicRead( gatt: BluetoothGatt, characteristic: BluetoothGattCharacteristic, status: Int ) { if (status == BluetoothGatt.GATT_SUCCESS) { val batteryLevel = BigInteger(characteristic.value) Log.d("BLE", "Battery level: $batteryLevel”) } } } -
• What thread are these requests running on? • What
thread are these callbacks running on? -
• What thread are these requests running on? • What
thread are these callbacks running on? • Is all this thread switching really needed? -
• What thread are these requests running on? • What
thread are these callbacks running on? • Is all this thread switching really needed? • What if we're already on a background thread? -
• Make assumptions about the client's execution requirements • Less
expressive / complicated statement flow (goto) -
• Make assumptions about the client's execution requirements • Less
expressive / complicated statement flow (goto) • Couple business logic with execution logic -
• Make assumptions about the client's execution requirements • Less
expressive / complicated statement flow (goto) • Couple business logic with execution logic • Harder to mock -
• Make assumptions about the client's execution requirements • Less
expressive / complicated statement flow (goto) • Couple business logic with execution logic • Harder to mock • Harder to debug -
• Make assumptions about the client's execution requirements • Less
expressive / complicated statement flow (goto) • Couple business logic with execution logic • Harder to mock • Harder to debug • Harder to handle errors -
• Make assumptions about the client's execution requirements • Less
expressive / complicated statement flow (goto) • Couple business logic with execution logic • Harder to mock • Harder to debug • Harder to handle errors • Asynchronism is overly fine-grained -
class SuspendableBluetoothLeScanner(private val context: Context) { suspend fun scan() =
callbackFlow { val scanCallback = object : ScanCallback() { } } } -
class SuspendableBluetoothLeScanner(private val context: Context) { suspend fun scan() =
callbackFlow { val scanCallback = object : ScanCallback() { override fun onScanResult(callbackType: Int, result: ScanResult) { } } } } -
class SuspendableBluetoothLeScanner(private val context: Context) { suspend fun scan() =
callbackFlow { val scanCallback = object : ScanCallback() { override fun onScanResult(callbackType: Int, result: ScanResult) { if (!isClosedForSend) { offer(SuspendableBluetoothDevice(context, result.device)) } } } } } -
class SuspendableBluetoothLeScanner(private val context: Context) { suspend fun scan() =
callbackFlow { val scanCallback = object : ScanCallback() { override fun onScanResult(callbackType: Int, result: ScanResult) { if (!isClosedForSend) { offer(SuspendableBluetoothDevice(context, result.device)) } } } with(BluetoothAdapter.getDefaultAdapter().bluetoothLeScanner) { startScan(scanCallback) } } } -
class SuspendableBluetoothLeScanner(private val context: Context) { suspend fun scan() =
callbackFlow { val scanCallback = object : ScanCallback() { override fun onScanResult(callbackType: Int, result: ScanResult) { if (!isClosedForSend) { offer(SuspendableBluetoothDevice(context, result.device)) } } } with(BluetoothAdapter.getDefaultAdapter().bluetoothLeScanner) { startScan(scanCallback) awaitClose { stopScan(scanCallback) } } } } -
sealed class GattEvent { class OnConnectionStateChange(val newState: Int) : GattEvent()
class OnServicesDiscovered(val services: List<BluetoothGattService>) : GattEvent() class OnCharacteristicRead(val characteristic: BluetoothGattCharacteristic) : GattEvent() object Error : GattEvent() } -
class CoroutineGattCallback : BluetoothGattCallback() { private val _eventsChannel = BroadcastChannel<GattEvent>(Channel.BUFFERED)
val eventsChannel: ReceiveChannel<GattEvent> get() = _eventsChannel.openSubscription() } -
class CoroutineGattCallback : BluetoothGattCallback() { private val _eventsChannel = BroadcastChannel<GattEvent>(Channel.BUFFERED)
val eventsChannel: ReceiveChannel<GattEvent> get() = _eventsChannel.openSubscription() override fun onConnectionStateChange(gatt: BluetoothGatt, status: Int, newState: Int) { } } -
class CoroutineGattCallback : BluetoothGattCallback() { private val _eventsChannel = BroadcastChannel<GattEvent>(Channel.BUFFERED)
val eventsChannel: ReceiveChannel<GattEvent> get() = _eventsChannel.openSubscription() override fun onConnectionStateChange(gatt: BluetoothGatt, status: Int, newState: Int) { if (status == BluetoothGatt.GATT_SUCCESS) { _eventsChannel.offer(GattEvent.OnConnectionStateChange(newState)) } else { _eventsChannel.offer(GattEvent.Error) } } } -
class CoroutineGattCallback : BluetoothGattCallback() { private val _eventsChannel = BroadcastChannel<GattEvent>(Channel.BUFFERED)
val eventsChannel: ReceiveChannel<GattEvent> get() = _eventsChannel.openSubscription() override fun onConnectionStateChange(gatt: BluetoothGatt, status: Int, newState: Int) { if (status == BluetoothGatt.GATT_SUCCESS) { _eventsChannel.offer(GattEvent.OnConnectionStateChange(newState)) } else { _eventsChannel.offer(GattEvent.Error) } } } -
class CoroutineGattCallback : BluetoothGattCallback() { private val _eventsChannel = BroadcastChannel<GattEvent>(Channel.BUFFERED)
val eventsChannel: ReceiveChannel<GattEvent> get() = _eventsChannel.openSubscription() override fun onConnectionStateChange(gatt: BluetoothGatt, status: Int, newState: Int) {…} } -
class CoroutineGattCallback : BluetoothGattCallback() { private val _eventsChannel = BroadcastChannel<GattEvent>(Channel.BUFFERED)
val eventsChannel: ReceiveChannel<GattEvent> get() = _eventsChannel.openSubscription() override fun onConnectionStateChange(gatt: BluetoothGatt, status: Int, newState: Int) {…} } -
class CoroutineGattCallback : BluetoothGattCallback() { override fun onConnectionStateChange(gatt: BluetoothGatt, status:
Int, newState: Int) {…} override fun onServicesDiscovered(gatt: BluetoothGatt, status: Int) { } } -
class CoroutineGattCallback : BluetoothGattCallback() { override fun onConnectionStateChange(gatt: BluetoothGatt, status:
Int, newState: Int) {…} override fun onServicesDiscovered(gatt: BluetoothGatt, status: Int) { if (status == BluetoothGatt.GATT_SUCCESS){ _eventsChannel.offer(GattEvent.OnServicesDiscovered(gatt.services)) } else { _eventsChannel.offer(GattEvent.Error) } } } -
class CoroutineGattCallback : BluetoothGattCallback() { override fun onConnectionStateChange(gatt: BluetoothGatt, status:
Int, newState: Int) {…} override fun onServicesDiscovered(gatt: BluetoothGatt, status: Int) { if (status == BluetoothGatt.GATT_SUCCESS){ _eventsChannel.offer(GattEvent.OnServicesDiscovered(gatt.services)) } else { _eventsChannel.offer(GattEvent.Error) } } } -
class CoroutineGattCallback : BluetoothGattCallback() { override fun onConnectionStateChange(gatt: BluetoothGatt, status:
Int, newState: Int) {…} override fun onServicesDiscovered(gatt: BluetoothGatt, status: Int) {…} } -
class CoroutineGattCallback : BluetoothGattCallback() { override fun onConnectionStateChange(gatt: BluetoothGatt, status:
Int, newState: Int) {…} override fun onServicesDiscovered(gatt: BluetoothGatt, status: Int) {…} override fun onCharacteristicRead( gatt: BluetoothGatt, characteristic: BluetoothGattCharacteristic, status: Int ) { } } -
class CoroutineGattCallback : BluetoothGattCallback() { override fun onConnectionStateChange(gatt: BluetoothGatt, status:
Int, newState: Int) {…} override fun onServicesDiscovered(gatt: BluetoothGatt, status: Int) {…} override fun onCharacteristicRead( gatt: BluetoothGatt, characteristic: BluetoothGattCharacteristic, status: Int ) { if (status == BluetoothGatt.GATT_SUCCESS) { _eventsChannel.offer(GattEvent.OnCharacteristicRead(characteristic)) } else { _eventsChannel.offer(GattEvent.Error) } } } -
class SuspendableBluetoothDevice( private val context: Context, private val bluetoothDevice: BluetoothDevice
) { private var gatt: BluetoothGatt? = null private val callback = CoroutineGattCallback() } -
class SuspendableBluetoothDevice( private val context: Context, private val bluetoothDevice: BluetoothDevice
) { private var gatt: BluetoothGatt? = null private val callback = CoroutineGattCallback() suspend fun connect(): Boolean { } } -
suspend fun connect(): Boolean { with(callback.eventsChannel.consumeAsFlow()) { gatt = bluetoothDevice.connectGatt(context,
false, callback) return map { when (it) { is GattEvent.OnConnectionStateChange -> it.newState == BluetoothGatt.STATE_CONNECTED is GattEvent.Error -> false else -> null } } } } -
suspend fun connect(): Boolean { with(callback.eventsChannel.consumeAsFlow()) { gatt = bluetoothDevice.connectGatt(context,
false, callback) return map { when (it) { is GattEvent.OnConnectionStateChange -> it.newState == BluetoothGatt.STATE_CONNECTED is GattEvent.Error -> false else -> null } }.filterNotNull() } } -
suspend fun connect(): Boolean { with(callback.eventsChannel.consumeAsFlow()) { gatt = bluetoothDevice.connectGatt(context,
false, callback) return map { when (it) { is GattEvent.OnConnectionStateChange -> it.newState == BluetoothGatt.STATE_CONNECTED is GattEvent.Error -> false else -> null } }.filterNotNull().first() } } -
suspend fun connect(): Boolean { with(callback.eventsChannel.consumeAsFlow()) { gatt = bluetoothDevice.connectGatt(context,
false, callback) return map { when (it) { is GattEvent.OnConnectionStateChange -> it.newState == BluetoothGatt.STATE_CONNECTED is GattEvent.Error -> false else -> null } }.filterNotNull().first() } } -
class SuspendableBluetoothDevice( private val context: Context, private val bluetoothDevice: BluetoothDevice
) { private var gatt: BluetoothGatt? = null private val callback = CoroutineGattCallback() suspend fun connect(): Boolean {…} } -
class SuspendableBluetoothDevice( private val context: Context, private val bluetoothDevice: BluetoothDevice
) { private var gatt: BluetoothGatt? = null private val callback = CoroutineGattCallback() suspend fun connect(): Boolean {…} suspend fun discoverServices() = gatt?.let { } ?: emptyList() } -
class SuspendableBluetoothDevice( private val context: Context, private val bluetoothDevice: BluetoothDevice
) { private var gatt: BluetoothGatt? = null private val callback = CoroutineGattCallback() suspend fun connect(): Boolean {…} suspend fun discoverServices() = gatt?.let { with(callback.eventsChannel.consumeAsFlow()) { it.discoverServices() filterIsInstance<GattEvent.OnServicesDiscovered>().first().services } } ?: emptyList() } -
class SuspendableBluetoothDevice( private val context: Context, private val bluetoothDevice: BluetoothDevice
) { private var gatt: BluetoothGatt? = null private val callback = CoroutineGattCallback() suspend fun connect(): Boolean {…} suspend fun discoverServices() = gatt?.let { with(callback.eventsChannel.consumeAsFlow()) { it.discoverServices() filterIsInstance<GattEvent.OnServicesDiscovered>().first().services } } ?: emptyList() } -
class SuspendableBluetoothDevice( private val context: Context, private val bluetoothDevice: BluetoothDevice
) { private var gatt: BluetoothGatt? = null private val callback = CoroutineGattCallback() suspend fun connect(): Boolean {…} suspend fun discoverServices() = gatt?.let {…} ?: emptyList() } -
class SuspendableBluetoothDevice( private val context: Context, private val bluetoothDevice: BluetoothDevice
) { private var gatt: BluetoothGatt? = null private val callback = CoroutineGattCallback() suspend fun connect(): Boolean {…} suspend fun discoverServices() = gatt?.let {…} ?: emptyList() suspend fun readCharacteristic(characteristic: BluetoothGattCharacteristic) = gatt?.let { } } -
suspend fun readCharacteristic(characteristic: BluetoothGattCharacteristic) = gatt?.let { with(callback.eventsChannel.consumeAsFlow()) { it.readCharacteristic(characteristic)
filterIsInstance<GattEvent.OnCharacteristicRead>().first().characteristic } } -
suspend fun readCharacteristic(characteristic: BluetoothGattCharacteristic) = gatt?.let { with(callback.eventsChannel.consumeAsFlow()) { it.readCharacteristic(characteristic)
filterIsInstance<GattEvent.OnCharacteristicRead>().first().characteristic } } -
class SuspendableBluetoothDevice( private val context: Context, private val bluetoothDevice: BluetoothDevice
) { private var gatt: BluetoothGatt? = null private val callback = CoroutineGattCallback() suspend fun connect(): Boolean {…} suspend fun discoverServices() = gatt?.let {…} ?: emptyList() suspend fun readCharacteristic(characteristic: BluetoothGattCharacteristic) = gatt?.let {…} } -
val bluetoothLeScanner = SuspendableBluetoothLeScanner(context) val bluetoothDevice = bluetoothLeScanner.scan().first() with(bluetoothDevice) {
if (connect()) { val services = discoverServices() } } -
val bluetoothLeScanner = SuspendableBluetoothLeScanner(context) val bluetoothDevice = bluetoothLeScanner.scan().first() with(bluetoothDevice) {
if (connect()) { val services = discoverServices() val batteryService = services.firstOrNull { it.uuid == BATTERY_SERVICE_UUID } } } -
val bluetoothLeScanner = SuspendableBluetoothLeScanner(context) val bluetoothDevice = bluetoothLeScanner.scan().first() with(bluetoothDevice) {
if (connect()) { val services = discoverServices() val batteryService = services.firstOrNull { it.uuid == BATTERY_SERVICE_UUID } batteryService?.characteristics?.firstOrNull { it.uuid == BATTERY_CHAR_UUID } } } } -
val bluetoothLeScanner = SuspendableBluetoothLeScanner(context) val bluetoothDevice = bluetoothLeScanner.scan().first() with(bluetoothDevice) {
if (connect()) { val services = discoverServices() val batteryService = services.firstOrNull { it.uuid == BATTERY_SERVICE_UUID } batteryService?.characteristics?.firstOrNull { it.uuid == BATTERY_CHAR_UUID }?.let { val batteryLevel = readCharacteristic(it)?.value Log.d("BLE", "Battery level: ${BigInteger(batteryLevel)}”) } } } -
val bluetoothLeScanner = SuspendableBluetoothLeScanner(context) val bluetoothDevice = bluetoothLeScanner.scan().first() with(bluetoothDevice) {
if (connect()) { val services = discoverServices() val batteryService = services.firstOrNull { it.uuid == BATTERY_SERVICE_UUID } batteryService?.characteristics?.firstOrNull { it.uuid == BATTERY_CHAR_UUID }?.let { val batteryLevel = readCharacteristic(it)?.value Log.d("BLE", "Battery level: ${BigInteger(batteryLevel)}”) } } else { Log.d("BLE", "Error connecting to device") } } -
val bluetoothLeScanner = SuspendableBluetoothLeScanner(context) val bluetoothDevice = bluetoothLeScanner.scan().first() with(bluetoothDevice) {
if (connect()) { val services = discoverServices() val batteryService = services.firstOrNull { it.uuid == BATTERY_SERVICE_UUID } batteryService?.characteristics?.firstOrNull { it.uuid == BATTERY_CHAR_UUID }?.let { val batteryLevel = readCharacteristic(it)?.value Log.d("BLE", "Battery level: ${BigInteger(batteryLevel)}”) } } else { Log.d("BLE", "Error connecting to device") } } -
• Async APIs sometimes can be confusing and hard to
follow • Avoid making assumptions about execution requirements -
• Async APIs sometimes can be confusing and hard to
follow • Avoid making assumptions about execution requirements • Code should be linear like a recipe for better expressiveness -
• Async APIs sometimes can be confusing and hard to
follow • Avoid making assumptions about execution requirements • Code should be linear like a recipe for better expressiveness • Coroutines can help clean up callback-heavy APIs