예시
예시
- flatMap: 다 실행
- flatMapLatest: 최신만
- flatMapFirst: 첫 번째만
기존 방식에서는 데이터 배열을 직접 관리하고, 변경 시 UICollectionView에 다시 그리도록 요청한다.
items = newItems
collectionView.reloadData()
또는 삽입/삭제 시 직접 indexPath를 계산해서 업데이트해야 한다.
reloadData()는 변경되지 않은 셀까지 모두 다시 그림Invalid update 크래시 발생 가능👉 즉, 데이터 상태와 UI 상태를 직접 맞춰야 하는 부담이 존재
Diffable DataSource는 이전 데이터와 새로운 데이터의 차이를 자동으로 계산하여 UI를 업데이트하는 방식이고 UI를 직접 조작하는 대신, 현재 상태(snapshot)를 전달한다.
dataSource = UICollectionViewDiffableDataSource<Section, String>(
collectionView: collectionView
) { collectionView, indexPath, item in
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath)
var content = UIListContentConfiguration.cell()
content.text = item
cell.contentConfiguration = content
return cell
}
var snapshot = NSDiffableDataSourceSnapshot<Section, String>()
snapshot.appendSections([.main])
snapshot.appendItems(items, toSection: .main)
dataSource.apply(snapshot, animatingDifferences: true)
items = newItems
collectionView.reloadData()
items = newItems
applySnapshot(items: items)
struct MusicItem: Hashable {
let id: Int
let title: String
}
Diffable DataSource는 데이터 상태(snapshot)를 기반으로 UI를 자동 업데이트하여, 안정성과 유지보수성을 높여주는 방식이다.