Last active
November 5, 2020 07:27
-
-
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).
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
ForEach(viewModel.repos) { repo in | |
RepositoryRow(repo: repo) | |
.onAppear( | |
ofViewRelatedTo: repo, | |
from: viewModel.repos, | |
inSuffixOfLength: 10, | |
perform: viewModel.fetchNextPageIfPossible | |
) | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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