How to chain transformations in Android when using live data?

Given the following setup:

I have 2 repositories: Repository A and Repository B both of them return live data.

I have a ViewModel that uses both of these repositories.

I want to extract something from Repository A and depending on the result I want to grab something from Repository B and then transform the result before returning to UI.

For this I have been looking at the LiveData Transformation classes. The examples show a single transformation of the result however I want something along the lines of chaining two transformations. How can I accomplish this?

I have tried setting something up like this but get a type mismatch on the second transformation block:

  internal val launchStatus: LiveData<String> = Transformations
        .map(respositoryA.getData(), { data ->
            if (data.isValid){
                "stringA"
            } else {
                //This gives a type mismatch for the entire block
                Transformations.map(repositoryB.getData(), {
                    result -> result.toString()
                })
            }
        })

(Also please let me know if there is an alternate/recommended approach for grabbing something for chaining these call i.e. grab something from A and then grab something from B depending on result of A and so on)

1 answer

  • answered 2017-11-12 20:49 Salvatore-Giordano

    I would try using switchMap instead of map:

    Similar to map(), applies a function to the value stored in the LiveData object and unwraps and dispatches the result downstream. The function passed to switchMap() must return a LiveData object.