Last active
May 29, 2020 23:45
-
-
Save pitt500/0c655b324d7df94d7efa3e031c1b65e5 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
//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