#RxAndroid: replace anonymous #callback functions
Posted on November 11th, 2015
11/10/2015 @AmericanExpress, 200 Vesey Street, NY
Trevor John and Alex Matchneer spoke about the advantages of using RxAndroid, an Android adaptation of #RxJava, to simplify the handling of asynchronous events.
Trevor John @PlayDraft introduced the Rx concepts of observables and subscribers. Observables are functions that handle externally triggered events, such as button presses or updates from external devices. The observables can filter and manipulate the results, but are not executed until a subscriber subscribes to it. The structure of observers and subscribers, along with the lambda style of function calls, removes the need for anonymous function calls that were the prior basis for event handling.
Trevor then spoke about the new requirements to create unit tests with RxAndroid. The challenge is to create functions without the extended syntax needed to specify mock events. He talked about some methods to simplify the test code and concluded with general advice on testing
- Keep test names short, so you know what it tests e.g.: methodName_context_assertion()
- Keep tests short
- Limit assertions per test
In the second presentation, Alex Matchneer @FutureProofRetail spoke about lesson learned in extending the functionality of FutureProofRetail’s mobile app. The company has an app which allows customers to purchase grocery items in the store using their mobile app. This allows the customer to skip the checkout line. The initial app has been extended to include item that needs to be weighed. To do this they interfaced a tablet with a scale (using USB), so that customers could weigh items and see a bar code displayed on the tablet. Customers scan the bar code on their mobile phone to include it in their shopping basket.
To streamline the programming logic Alex used Rx.
He created an observable which
- Received a character string showing weights from the USB interface with the scale
- Filter out strings missing units, decimal points, etc.
- Eliminate spurious weights
- Wait for the weight to stabilize before displaying the bar code
- If the scale is unused, display the “how to use” video on the screen
Alex showed how specific functions in Rx performed these functions
- A series of functions specify when a value is received, if the values are repeated, etc.
- The filter command removes strings that are not consistent with a regular expression
- The buffer command groups individual observations into a overlapping or non-overlapping arrays so the function can easily remove the max and min values and calculate the mean for the remaining values
- The switchmap function shows the bar code if the weight is stable for ½ second.
- Switchmap can also be used to trigger the video if the scale is currently unused
The observer-subscriber dichotomy simplifies the organization of the code and makes it robust to events triggered by inputs from the scale and user actions.