REACTIVE PROGRAMMINGMaking Network Calls with LiveData TransformationsUsing map() and switchMap() for chaining network calls
Photo by Chris Lawton on Unsplash
Reactive programming has been trending in Android for quite some time now, mainly because it simplifies the process of writing async code. LiveData is a variant of the original observer pattern, with the addition of active/inactive transitions, allowing communication between the data source and other UI components. With LiveData, comes Transformations, which provides a better way to perform manipulations on the LiveData instance. Think of Transformations as Util class for LiveData that helps in modifying the data as required. In this article, we shall explore how
Getting StartedWe have made two network calls throughout the app which are taken from these open APIs
The sample app is responsible for,
TL;DRFirst network call returns the list that is used to populate the spinner. Second network call returns the details of the selected item. Let us try to understand why/how this is implemented.
Here is a high-level architecture diagram to understand how data flows between different components
High-level Architecture Diagram
In the sample app,
Here, depending upon the failure/success of the API call, we wrap the response in Transformations.map()This is a very simple and straightforward way to create the transformation. This method takes in LiveData as a function parameter and observes it for any change in value. Whenever a new value is available, it applies the transformation on the data and returns the transformed LiveData to the observers.
With this, we have achieved the first task of populating the spinner with a list of dog breeds. Now, we need to fetch the details of the user-selected item. We can make a network call in the click listener of the spinner but there is a more cleaner and concise way of implementing this functionality using switchMap()
Transformations.switchMap()
Hence, this kind of chaining helps us in performing tasks that are dependant on each other. The architecture can look much cleaner and concise as long as you don’t chain too many tasks. That’s all for this article, let me know your thoughts on this approach. You can find the sample app on GitHub:
Feel free to Fork it/contribute to it. Happy Coding!
Android News
droidcon News
Tech Showcases, Developer Resources & Partners
EmployerBrandingHeader
jobs.droidcon.com
![]() Latest Android Jobs
Kotlin Weekly
![]() Your weekly dose of Kotlin
ProAndroidDev
![]() Android Tech Blogs, Case Studies and Step-by-Step Coding
Zalando
![]() Meet one of Berlin's top employers
Academy for App Success
![]() Google Play resources tailored for the global droidcon community |
Droidcon is a registered trademark of Mobile Seasons GmbH Copyright © 2020. All rights reserved.