Skip to content

Instantly share code, notes, and snippets.

@Czajnikowski
Last active November 5, 2020 07:27
Show Gist options
  • Save Czajnikowski/49d0f70795293c631fe4a9847d23d27f to your computer and use it in GitHub Desktop.
Save Czajnikowski/49d0f70795293c631fe4a9847d23d27f to your computer and use it in GitHub Desktop.
My pragmatic take on infinite scrolling/lazy loading in the SwiftUI. Given example performs `fetchNextPageIfPossible` when the row that appeared is related to the one of the last 10 of models (Identifiable-s).
ForEach(viewModel.repos) { repo in
RepositoryRow(repo: repo)
.onAppear(
ofViewRelatedTo: repo,
from: viewModel.repos,
inSuffixOfLength: 10,
perform: viewModel.fetchNextPageIfPossible
)
}
extension View {
func onAppear<Id, Ids>(
ofViewRelatedTo identifier: Id,
from identifiers: Ids,
inSuffixOfLength suffixLength: Int,
perform: @escaping () -> Void
) -> some View
where Id: Identifiable,
Ids: Sequence,
Ids.Element == Id
{
return onAppear {
if identifiers
.suffix(suffixLength)
.contains(where: { $0.id == identifier.id })
{
perform()
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment