4

How to enable data prefetching when using the new Compositional Layout & DiffableDataSource?

Before, we can achieve this by conforming a custom data source object, like,

class CustomDataSource: NSObject, UICollectionViewDataSource, UICollectionViewDataSourcePrefetching

Now, the data source is the UICollectionViewDiffableDataSource, which only conforms to UICollectionViewDataSource.

One way is to extend it to conform to the prefetching protocol. However, due to the fact that it encapsulates protocol implementations of the DataSource into its higher level methods like snapshots and apply. I can't figure out how to extend it to conforms to the prefetching protocol.

zrfrank
  • 2,631
  • 1
  • 12
  • 18

1 Answers1

2

Your implementation of UICollectionViewDataSourcePrefetching is set on a separate property of UICollectionView called prefetchDataSource. So you should not need to subclass UICollectionViewDiffableDataSource

https://developer.apple.com/documentation/uikit/uicollectionview/1771768-prefetchdatasource

I can confirm that prefetching works when using a UICollectionViewDiffableDataSource. You will need to cache your prefetched data somewhere, and then access it from your cellProvider (or UICollectionView.CellRegistration)

For example, if your view controller implements UICollectionViewDataSourcePrefetching then you may have a line where you assign it as the prefetchDataSource:

myCollectionView.prefetchDataSource = self
simeon
  • 4,466
  • 2
  • 38
  • 42
  • 3
    Note that with Compositional Layout if you use `.estimated()` in a dimension of `NSCollectionLayoutSize` in your `UICollectionViewCompositionalLayout` then the prefetching data source is never called. I couldn't figure out why this wasn't working for me until I discovered that fact. – Devin Pitcher Jun 27 '21 at 20:42
  • @DevinPitcher would you please share where you read such info. – Ahmed Shendy Sep 12 '21 at 11:33
  • 1
    @AhmedShendy it's been long enough I don't remember if I read it some where or discovered it on my own. This SO question describes the same issue https://stackoverflow.com/q/62726919/3067557. – Devin Pitcher Sep 16 '21 at 03:01