Functional UI programming
What is an App?
State => UI
A program is just a finite state machine.
Separation of concern
- Modular component allows local reasoning about state changes
- Layers separate the levels of abstraction
- Horizontal and vertical scaling
A component focuses on a single feature
- Template editing
- Auditing
- Exports
A layer is responsible for abstraction and interface
- Activity (navigation, workflow)
- Fragment (drop-in view component)
- Adapter (connect data and views)
- View (generic view rendering)
- Data model
- Persistence (database, file, network)
Data Binding
- Bind views to view states
- Motivation: reduce boilerplate code
- Generic interface
Mutable value
public interface Mutable<T> {
T getValue();
void setValue(T value);
}
Why bother to wrap to value?
- Better Control of getter and setter
- Can add data validation in getter
- Can add hooks in setter
public static void bindCheckBox(CheckBox checkBox, final Mutable<Boolean> value)
{
checkBox.setChecked(value.getValue());
checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener()
{
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
{
value.setValue(isChecked);
}
});
}
/**
* Bind the radio buttons to a set of values
* @param radioGroup
* @param model
* @param map a bidirectional map from values to radio button ids, and it must be 1:1 relationship.
*/
public static <T> void bindRadioGroup(final RadioGroup radioGroup, final Mutable<T> model, final BiMap<T, Integer> map)
{
T value = model.getValue();
int id = map.get(value);
radioGroup.check(id);
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener()
{
@Override
public void onCheckedChanged(RadioGroup group, int checkedId)
{
T newValue = map.inverse().get(checkedId);
model.setValue(newValue);
}
});
}
MVVM
The view model acts as an intermediary between the view and the model, and is responsible for handling the view logic.
Data Binding
- Bind UI widgets to states in ViewModel
- Bind user interactions to actions (operations) in view models
- View Model is like a mock of the view, enabling easy testing
- View model is synchronised to model
MVVM in Android
Activity
Fragment
Adapter
View Model
View
Data
App States
FunUI
By James Deng
FunUI
- 533