Skip to content

Data source

Diego Sánchez edited this page Jul 4, 2016 · 1 revision

Data source

Provides the collection of messages that will be rendered (actually the Decorator has the last word), and receives callbacks from the view controller to load more messages:

public protocol ChatDataSourceProtocol: class {
    var hasMoreNext: Bool { get }
    var hasMorePrevious: Bool { get }
    var chatItems: [ChatItemProtocol] { get }
    weak var delegate: ChatDataSourceDelegateProtocol? { get set }

    func loadNext() // Should trigger chatDataSourceDidUpdate with UpdateType.Pagination
    func loadPrevious() // Should trigger chatDataSourceDidUpdate with UpdateType.Pagination
    func adjustNumberOfMessages(preferredMaxCount preferredMaxCount: Int?, focusPosition: Double, completion:(didAdjust: Bool) -> Void) // If you want, implement message count contention for performance, otherwise just call completion(false)
}

These are the requirements of the messages

public protocol ChatItemProtocol: class {
    var uid: String { get }
    var type: ChatItemType { get }
}

The uid is a plain String used to calculate insertions/deletions to perform an animated update in the UICollectionView. The type property is a help for the PresenterFactory so we can quickly find a PresenterBuilder for the chat item. @see Presenters and BaseChatViewController to know more about Presenters.

When there's a change in the collection of messages it must notify the view controller:

public protocol ChatDataSourceDelegateProtocol: class {
    func chatDataSourceDidUpdate(chatDataSource: ChatDataSourceProtocol, updateType: UpdateType)
}

The updateType parameter tells how the update should be performed:

public enum UpdateType {
    case normal
    case firstLoad
    case pagination
    case reload
    case messageCountReduction
}

As of today, pagination, reload and messageCountReduction behave exactly the same: they will trigger a reloadData of the UICollectionView.

firstLoad will do a reloadData as well, but it will force the layout to be calculated in the main thread. This is useful when presenting the view controller to avoid showing an empty screen for a short time (especially on slow devices)

Lastly, normal will trigger a performBatchUpdates in the UICollectionView. All the insertions and deletions will be calculated by Chatto in a background thread using the uids of the ChatItemProtocol

Learn more about the Update flow

Clone this wiki locally