LiveData Transformations

Sometimes, the data that you want is not the data that you get:

The LiveData system has some limited support for “transformations”, which help you adapt an existing LiveData into one that changes the data to better suit your needs. You can also create your own transformations, if desired. In this chapter, we will explore all of this.

The Bucket Brigade

LiveData is designed to be a simplified form of a reactive framework like RxJava.

Anyone who has looked at RxJava code knows that it has a tendency towards long chains of calls, to configure a stream of data, and sometimes to modify that stream along the way.

For example, you will find code like:

Observable<String> observable=Observable
  .create(new WordSource(getActivity()))
  .subscribeOn(Schedulers.io())
  .map(s -> (s.toUpperCase()))
  .observeOn(AndroidSchedulers.mainThread())
  .doOnComplete(() -> {
    Toast.makeText(getActivity(), R.string.done, Toast.LENGTH_SHORT)
      .show();
  });

Here, we:

In particular, map() is a transformation “operator”, in Rx terms. map() takes an object from our stream of data (in this case, a word) and transforms it into something else, which flows downstream to the subsequent chained calls. In this case, map() transforms a String into a String, where the “transformation” is converting the input String to uppercase to use as the output String.

RxJava has a dozens of such operators. In contrast, LiveData has two, and we will implement a third ourselves to see how that is accomplished.


Prev Table of Contents Next

This book is licensed under the Creative Commons Attribution-ShareAlike 4.0 International license.