Skip to content

Instantly share code, notes, and snippets.

@pitt500
Last active May 29, 2020 23:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pitt500/0c655b324d7df94d7efa3e031c1b65e5 to your computer and use it in GitHub Desktop.
Save pitt500/0c655b324d7df94d7efa3e031c1b65e5 to your computer and use it in GitHub Desktop.
//1
class ItemListViewModel: ObservableObject {
//2
@Published var items: [Int] = []
//3
static private var itemsPerPage = 25
private var start = -ItemListViewModel.itemsPerPage
private var stop = -1
private let maxData = 250
private func incrementPaginationIndices() {
start += ItemListViewModel.itemsPerPage
stop += ItemListViewModel.itemsPerPage
stop = min(maxData, stop)
}
private func retrieveDataFromAPI(completion: (() -> Void)? = nil) {
DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) { [weak self] in
guard let self = self else { return }
let newData = Array(self.start...self.stop)
self.items.append(contentsOf: newData)
completion?()
}
}
//4
func getData(completion: (() -> Void)? = nil) {
if start > maxData {
completion?()
return
}
incrementPaginationIndices()
retrieveDataFromAPI(completion: completion)
}
}
//5
extension Int: Identifiable {
public var id: Int {
return self
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment