'UITableView w/ optimistic UI updates in iOS
I have a UITableView that contains a number of 'likeable' items.
This status can be toggled via a UIButton in the cell.
I'd like to update the UI to reflect changes when a user un/likes an item in an optimistic fashion. Should the operation fail, I will then roll back these values.
I am trying to understand how to implement this change without complication the design of my application.
Currently I have 3 layers;
- API
- Presentation
- UI
Each layer communicates via adapters that map between delegates and interfaces to avoid coupling the implementations.
The Presentation layer maps a RemoteFeedItem into a FeedItemViewModel which a FeedItemCellController will then use to prepare a UITableViewCell.
The FeedItemViewModel contains only the values for the UI in the correct state/type.
For example the 'likes' count is now a String not an Int so this can be rendered by a UILabel
My UITableView has an array of FeedItemCellController's which are used in cellForRowAt.
I am trying to understand where the best place for this optimistic UI change to take place is.
Updating the value in the cell on tap works, however should the user scroll before the async operation is completed the change reverts when the cell is reused as the original model is unchanged.
If I make a change in the model, this will persist across cell reuse, however I need to keep a reference to the updated model somewhere - the issue here is I now have 2 sources of truth for my cell -
- The model produced by the Presentation layer
- My local copy, updated with the new status
Is this OK - under the assumption both will be eventually consistent?
Or should the Presentation layer be notified of the action and produce a new model based on this?
That way of the action fails, it can produce a new model again with the reverted values?
I appreciate this may be an opinion point, but I am keen to find a way to implement this in a clean and testable fashion.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
