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.
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