How do I paginate API results in Combine with Swift?

Pagination is a common requirement when dealing with API results, especially when working with Combine in Swift. This allows you to fetch results in manageable chunks, thereby improving performance and user experience.

Keywords: Swift, Combine, API pagination, iOS, SwiftUI, Combine framework
Description: This example demonstrates how to paginate API results using Combine in Swift, ensuring efficient data fetching and improved app performance.

import Combine

class PaginationExample {
    var cancellables = Set()
    let apiClient = APIClient()
    
    var currentPage = 1
    var results: [YourDataModel] = []
    
    func fetchData() {
        apiClient.fetchResults(page: currentPage)
            .sink(receiveCompletion: { completion in
                switch completion {
                case .finished:
                    print("Finished fetching data")
                case .failure(let error):
                    print("Error fetching data: \(error)")
                }
            }, receiveValue: { newResults in
                self.results.append(contentsOf: newResults)
                self.currentPage += 1
            })
            .store(in: &cancellables)
    }
}

// Usage
let paginationExample = PaginationExample()
paginationExample.fetchData()
    

Keywords: Swift Combine API pagination iOS SwiftUI Combine framework