Asynchronous Android event handling (callbacks and eventbus)

I am currently developing an Android app with Bluetooth Low Energy capabilities. Android BLE (Bluetooth Low Energy) method calls are mostly (if not all) asynchronous in nature. I have encapsulated this BLE handling functionality in Service

and tried to separate other parts of the application from the "Android BLE Library concrete implementation / interface". Since the Android Bluetooth API is asynchronous, I am trying to "pass" Android BLE callbacks to the calling modules.

My use case is like below.

externalModuleInstance.getSomeProperty()

will call bleService.readCharacteristic(somePropertyId)

, and when some asynchronous operation is done on the Android BLE stack, bleService will be notified via the Android BLE result API callback. How do I pass this result back to the externalModuleInstance?

I came up with three options: callbacks, listeners, and EventBus (by greenrobot).

  • Listeners . I would define BleServiceInterface

    and define some methods onSomeEvent()

    and implement this interface in ExternalModule

    . Then I would register this instance ExternalModule

    as a BleService

    listener. It seems good that the interface declaration seems explicit and straightforward.
  • EventBus . I just love this module for its simplicity and elegance, but I don't think this is the correct use case for the event bus (in lowercase) because I am ExternalModule

    not interested in the specific class / type of event, but rather in the results BleService

    .
  • Callbacks . It looks like Downside has to define each class for each result type. I could use generics, but I would end up having to provide an event class (sort of C struct-looking), so I think they are the same thing. Also, the code would look a little more nested and complex if I decided to use on-the-fly instance callback classes and navigate to the method parameters. However, I feel like callbacks are the way to go in this case because it seems to be the right mechanism for getting the results of an asynchronous call, as it is for every method.

I am very interested in what others think about this issue and what to use in this situation, and possibly asynchronous event handling in general. Please feel free to correct and educate me!

+3


source to share





All Articles