Loading...
Home
  • Tech Blogs
  • Videos
  • Conferences
    • Droidcon News
    • Upcoming Conferences
    • Become a Partner
    • Past Events
    • Keep Me Informed
    • Diversity Scholarships
  • Community
    • droidcon Team
    • How to Hold a Droidcon
  • Android Careers
Sign In

Global CSS

REACTIVE PROGRAMMING

Making Network Calls with LiveData Transformations

Using map() and switchMap() for chaining network calls

 

 
Kunal Chaubal
Android Developer at Deloitte Digital
Published: July 07, 2020
Tweet
Share
 

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 Transformations.map() and Transformations.switchMap() can be used to make network calls in an MVVM architecture with the help of a sample application.

 

Getting Started

We have made two network calls throughout the app which are taken from these open APIs

 

Dog API

Read our documentation to find out more or try it out for yourself below. Want to add your dog to the collection…

dog.ceo

 

The sample app is responsible for,

  1. Fetching a list of Dog breeds and populate the same in the Spinner on the UI
  2. Based on the selection, fetch additional details by making another network call. Hence this network call is dependant on the value selected in the Spinner

 

 

TL;DR

First network call returns the list that is used to populate the spinner. Transformations.map()is used in this case.

Second network call returns the details of the selected item. Transformations.switchMap() is used in this case.

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

 

  • The Repository returns a LiveData instance of the response object.
  • In the ViewModel, the LiveData instance is passed as a parameter to map() or switchMap() . The transformations are calculated lazily, and will run only when the returned LiveData is being observed.
  • View is responsible for observing the LiveData and updating the UI once the response is received.

 

 

In the sample app, fetchDetails() returns a list of ‘DogBreed’ objects which is wrapped in ‘Resource’ before storing in LiveData with the help of asLiveData() extension.

fetchBreedDetails(id) requires a ‘DogBreed’ id as a param to return an object of ‘BreedDetails’ which is stored as LiveData in a similar manner.

 

 

Here, depending upon the failure/success of the API call, we wrap the response in Resource.error or Resource.success accordingly and store it in a MutableLiveData and return the same.


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.

 

 

  • In the sample app, we are transforming List<Resource<DogBreeds>> to List<String> which is needed to populate the ‘Select Dog Breed Spinner’ on the UI.
  • In case of a failed API call, the error can be handled and the UI could be updated accordingly.
  • Notice that a ‘LifecycleOwner’ is not needed here, although, without an observer, the transformation will never get triggered.
  • The LiveData that is being returned from fetchDogBreedList() is being observed from the fragment.

 

 

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()

 

 

  • selectedBreedLiveData is set whenever a new spinner value is selected. This is done in the onItemSelectedListener of the Spinner in the fragment
  • Observing breedDetailsLiveData will trigger a callback whenever selectedBreedLiveData is set.
  • Similar to map(), ‘LifecycleOwner’ is not needed here.
  • The LiveData that is being returned from fetchBreedDetails() is being observed from the fragment.

 

 

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:

 

KunalChaubal/LiveDataTransformExample

A sample app to showcase Transformations.map() and switchMap() to transform LiveData …

github.com

 

Feel free to Fork it/contribute to it.

Happy Coding!

 

 

Tags: Android, Livedata Transformations, Clean Architecture, AndroidDev, App Development

 

View original article at: 


 

Originally published: June 09, 2020

Android News
Evolution of Android Update SystemEvolution of Android Update System
Evolution of Android Update SystemEvolution of Android Update System

By Ivan Kuten

So, how can you update Android on mobile devices? While developing software for Smart TVs and Android-based set-top boxes, we’ve narrowed it down to four ways, discarding some very exotic options:

By ProAndroidDev -
Android News
Happy Railway
Happy Railway

By Hadi Lashkari Ghouchani

This post is on the tail of Railway Oriented Programming in Kotlin by Antony Harfield. So you need to read it first and continue here. As it’s obvious I really liked it and tried it out. It needs every process have a result like

By ProAndroidDev -
Android News
Unit Tests and Concurrency
Unit Tests and Concurrency

By Stojan Anastasov

Once Retrofit added RxJava support, RxJava became my go-to concurrency framework for writing Android apps. One of the great things about RxJava is the excellent testing support. It includes TestObserver, TestScheduler, RxJavaPlugins so you can switch your schedulers in tests.

By ProAndroidDev -
Android News
When Compat libraries will not save you
When Compat libraries will not save you

By Danny Preussler

And why you should avoid using the “NewApi” suppression! The idea of “Compat” libraries was probably one of the key aspects of Android dominating the mobile space. Other than with iOS, Android users often could not update their operating system after a new version launch, simply as their phones won’t allow them to, the Android problem of fragmentation.

 

By ProAndroidDev -
droidcon News

Tech Showcases,

Developer Resources &

Partners

/portal/rest/jcr/repository/collaboration/Groups/spaces/droidcon_hq/Documents/public/home-details/EmployerBrandingHeader
EmployerBrandingHeader
https://jobs.droidcon.com/
/portal/rest/jcr/repository/collaboration/Groups/spaces/droidcon_hq/Documents/public/employerbranding/jobs-droidcon/jobs.droidcon.com
jobs.droidcon.com

Latest Android Jobs

http://www.kotlinweekly.net/
/portal/rest/jcr/repository/collaboration/Groups/spaces/droidcon_hq/Documents/public/employerbranding/kotlin-weekly/Kotlin Weekly
Kotlin Weekly

Your weekly dose of Kotlin

https://proandroiddev.com/
/portal/rest/jcr/repository/collaboration/Groups/spaces/droidcon_hq/Documents/public/employerbranding/pad/ProAndroidDev
ProAndroidDev

Android Tech Blogs, Case Studies and Step-by-Step Coding

/detail?content-id=/repository/collaboration/Groups/spaces/droidcon_hq/Documents/public/employerbranding/Zalando/Zalando
/portal/rest/jcr/repository/collaboration/Groups/spaces/droidcon_hq/Documents/public/employerbranding/Zalando/Zalando
Zalando

Meet one of Berlin's top employers

/detail?content-id=/repository/collaboration/Groups/spaces/droidcon_hq/Documents/public/employerbranding/Academy for App Success/Academy for App Success
/portal/rest/jcr/repository/collaboration/Groups/spaces/droidcon_hq/Documents/public/employerbranding/Academy for App Success/Academy for App Success
Academy for App Success

Google Play resources tailored for the global droidcon community

Follow us

Team droidcon

Get in touch with us

Write us an Email

 

 

Quicklinks

> Code of Conduct

> Terms and Conditions

> How to hold a conference

> FAQs

> Imprint

Droidcon is a registered trademark of Mobile Seasons GmbH Copyright © 2020. All rights reserved.

powered by Breakpoint One