PavelPud
PavelPud

Reputation: 53

DiffableDataSource using 2 data models

I have a ViewController with a UICollectionView and a DiffableDataSource. Additionally, I have two entities: User and Chat.

Initially, my data source was defined as:

private var dataSource: UICollectionViewDiffableDataSource<Sections, AnyHashable>?

because I needed to handle two different models and two different cells accordingly.

However, one issue is that the data for ChatCell comes not only from the Chat model but also from some other managers at the moment of setting up the data source:

func setupDataSource() {
    dataSource = UICollectionViewDiffableDataSource<Sections, AnyHashable>(collectionView: collectionView, cellProvider: { [weak self] collectionView, indexPath, item in
        if let chatModel = item as? ChatModel, let chatId = chatModel.id {
            let cell = ChatCell.dequeue(collectionView, for: indexPath)
            let tags = self?.tagsManager.getTags(for: chatId)
            let status = self?.statusManager.getStatus(for: chatId)
            cell.fillData(chat: chatModel, tags: tags, status: status)
            return cell
            
        } else if let userModel = item as? User {
            let cell = UserCollectionCell.dequeue(collectionView, for: indexPath)
            cell.fillData(user: userModel)
            return cell
            
        } else {
            return UICollectionViewCell()
        }
    })
}

This approach makes it difficult to update the data in UICollectionView natively via DiffableDataSource. The only way I can update the data is through a method inside each ChatCell.

Here’s an approximate copy of my reloadDiffableDataSource method:

private func reloadDiffableDataSource(_ state: DataSourceState) {
    queue.async(flags: .barrier) {
        var snapshot = NSDiffableDataSourceSnapshot<Sections, AnyHashable>()
        
        switch state {
        case .main(let favoriteChats, let otherChats, let isShowFavourites):
            if !favoriteChats.isEmpty {
                snapshot.appendSections([.favorites])
                if isShowFavourites {
                    snapshot.appendItems(favoriteChats.values, toSection: .favorites)
                } else {
                    snapshot.appendItems([], toSection: .favorites)
                }
            }
    ...
    self.dataSource?.apply(snapshot, animatingDifferences: false)
}

How should I refactor the code to natively update the DiffableDataSource and UICollectionView using methods like snapshot.reconfigureItems(ids) or something similar?

I’ve tried to create a DTO for the chat properties but got stuck.

Upvotes: 1

Views: 63

Answers (0)

Related Questions