In UIKit we have UITableViewDataSourcePrefetching (https://andreygordeev.com/2017/02/20/uitableview-prefetching/).
I want to do something similar in SwiftUI in order to show a large collection of data, where all of it cannot be in memory at the same time.
I came up with a solution, where an invisible rectangle has an .onAppear callback which handles loading more data. The issue is that this makes the experience pretty slow, since the data isn't actually prefetched, but only loaded when we reach a point in table.
struct ContentView: View {
@ObjectBinding var elements: [Int]
var body: some View {
ForEach(elements.identified(by: \.self)) { element in
Text("\(element)")
}
Rectangle().opacity(0).onAppear {
// Add more data
}
}
}
I would like to be able to add this .onAppear event on an earlier element created by the ForEach, to actually fetch data before we have reached the end of the current data.
Another alternative I thought of was to create a custom collection, which in its subscript function loads more data if one of the last indicies is accessed. The issue with that solution is that SwiftUI access all indicies when the View is initially loaded.