Displaying paginated lists in Combine with Swift can enhance the user experience by efficiently loading data. This approach allows you to manage large datasets by breaking them into smaller, manageable chunks, loading more data as the user scrolls or requests it.
// Import Combine and SwiftUI
import SwiftUI
import Combine
struct ContentView: View {
@StateObject private var viewModel = PaginatedViewModel()
var body: some View {
List {
ForEach(viewModel.items, id: \.id) { item in
Text(item.name)
}
if viewModel.isLoading {
ProgressView()
}
}
.onAppear {
viewModel.loadMoreItems()
}
.onInfiniteScroll {
viewModel.loadMoreItems()
}
}
}
class PaginatedViewModel: ObservableObject {
@Published var items: [Item] = []
@Published var isLoading = false
private var currentPage = 1
func loadMoreItems() {
guard !isLoading else { return }
isLoading = true
// Replace with your own data fetching logic
let newItems = fetchData(page: currentPage)
items.append(contentsOf: newItems)
currentPage += 1
isLoading = false
}
// Dummy data fetching method
private func fetchData(page: Int) -> [Item] {
// Fetch and return array of items
return (1...10).map { Item(id: $0 + (page - 1) * 10, name: "Item \($0 + (page - 1) * 10)") }
}
}
struct Item: Identifiable {
let id: Int
let name: String
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?