I have a need to transform one type of data, returned by a LiveData object, into another form on a background thread to prevent UI lag.
In my specific case, I have:
MyDBRowobjects (POJOs consisting of primitivelongs andStrings);- a Room DAO instance emitting these via a
LiveData<List<MyDBRow>>; and - a UI expecting richer
MyRichObjectobjects (POJOs with the primitives inflated into e.g. date/time objects)
so I need to transform my LiveData<List<MyDBRow>> into a LiveData<List<MyRichObject>>, but not on the UI thread.
The Transformations.map(LiveData<X>, Function<X, Y>) method does this needed transformation, but I can't use this because it executes the transformation on the main thread:
Applies the given function on the main thread to each value emitted by
sourceLiveData and returns LiveData, which emits resulting values.The given function
funcwill be executed on the main thread.
What is a clean way to make LiveData transformations occur:
- somewhere off the main thread, and
- only as needed (i.e. only when something is observing the intended transformation)?