LiveData Transformations
Sometimes, the data that you want is not the data that you get:
- You want to capitalize those names before showing them in a list
- You want to restrict the results to some subset of what you are receiving
- You do not need the data, but rather some calculation made upon batches of the data, grouped by some key
- And so on
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:
- Request a roster of words (
create(new WordSource(getActivity()))
) - Ask to retrieve that roster on a background thread, as it involves disk I/O (
subscribeOn(Schedulers.io())
) - Convert the words to uppercase (
map(s -> (s.toUpperCase()))
) - Ask to get the results on the main application thread, so we can update our UI with these words (
observeOn(AndroidSchedulers.mainThread())
) - Show a
Toast
when we are done processing the words (doOnComplete() ...
)
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.