Connecting programatically to a Bluetooth device involves the following stages:
- Scanning for peripherals’ advertising
- Connecting to the peripheral via GATT
- Discovering the peripheral’s services
- Discovering the peripheral’s characteristics
- Reading and writing to a characteristic’s value and/or monitoring characteristic value change via a Notify
Each of these stages is asynchronous because each takes a relatively long time in computing terms. This means the code needs to call something but continue running to remain responsive to other events and later process the result of a stage via a callback from the Bluetooth library. The connection isn’t reliable because it’s wireless. Different kinds of failure, also notified via callbacks, require the code to go back one or more stages depending on the severity of the error.
All this gets very messy, confusing and difficult to understand in the resultant code. Reactive (Rx) programming attempts to solve such asynchronous complexity problems by using the Observable Pattern to broadcast and subscribe to values and other events from an Observable stream.
There are Reactive implementations such as RxSwift on iOS and RxJava on Android. There are also Bluetooth specific libraries such as RxBluetoothKit for iOS/OSX and RxAndroidBle that make asynchronous Bluetooth code in Swift/Java much easier to understand and maintain.
Reactive programming used to be very popular not just for asynchronous programming but also for general Android programming. It has fallen out use for general programming mainly due to Kotlin which is now the ‘latest thing’.
Naive developers have a tendency to want to use the ‘latest thing’ or ‘clever techniques’ while experienced developers choose the right tool for the job. A common error is to over-use and combine design patterns, such as observables, in simple scenarios, which hinders rather than simplifies understanding.
The nature and relative complexity of your project should determine whether it’s worth using Reactive code. It’s not necessary an ‘all or nothing’ decision. It’s possible to choose to use observable pattern techniques only in parts of code with extreme asynchronous complexity rather than in all the code.