Skip to content

Quick start with Payloads

Vitaly Vivchar edited this page Feb 22, 2018 · 1 revision

Step 1: Read about DiffUtil and Payloads

Step 2: Override equals and hashCode methods in your model

public static class YourViewModel implements ViewModel {

	public int getID() { /* your getter */ }

	public String getText() { /* your getter */ }

	public String getDescription() { /* your getter */ }

	@Override
	public boolean equals(final Object o) {
		/* your implementation */
	}

	@Override
	public int hashCode() {
		/* your implementation */
	}
}

Step 3: Create your DiffCallback class and implement getChangePayload method

private class YourDiffCallback extends DefaultDiffCallback<YourViewModel> {

	@Override
	public boolean areItemsTheSame(YourViewModel oldItem, YourViewModel newItem) {
		return oldItem.getID() == newItem.getID();
	}

	@Override
	public Object getChangePayload(YourViewModel oldItem, YourViewModel newItem) {
		if (!oldItem.getText().equals(newItem.getText())) {
			return TEXT_CHANGED;
		}
		if (!oldItem.getDescription().equals(newItem.getDescription())) {
			return DESCRIPTION_CHANGED;
		}
		return super.getChangePayload(oldItem, newItem);
	}
}

Step 3: Use the payload argument in your ViewBinder

mAdapter.registerRenderer(new ViewBinder<>(
		R.layout.your_item,
		YourViewModel.class,
		(model, finder, payloads) -> {
			if (payloads.isEmpty()) {
				/* full bind */
			} else {
				/* partially bind */
				final Object payload = payloads.get(0);
				if (payload.equals(TEXT_CHANGED)) {
					/* update text */
				} else if (payload.equals(DESCRIPTION_CHANGED)) {
					/* update description */
				}
			}
		}
));