How do I handle pull-to-refresh in Combine with Swift?

Handling pull-to-refresh in Combine with Swift combines the power of Combine framework with SwiftUI's refreshing capabilities. In this example, we will demonstrate how to implement a simple pull-to-refresh feature in a SwiftUI application using Combine to manage the data updates.

Pull-to-refresh, Combine, SwiftUI, Swift, Data Binding, Swift Programming

This example showcases how to effectively use Combine for managing state changes during a pull-to-refresh action in a SwiftUI application, enhancing user experience with reactive programming.


import SwiftUI
import Combine

// View Model
class ContentViewModel: ObservableObject {
    @Published var data: [String] = []
    var cancellables = Set()

    init() {
        // Initial data fetch
        fetchData()
    }

    func fetchData() {
        // Simulate a network call with a delay
        Just(["Data Item 1", "Data Item 2", "Data Item 3"])
            .delay(for: .seconds(1), scheduler: RunLoop.main)
            .assign(to: &$data)
    }
}

// SwiftUI View
struct ContentView: View {
    @ObservedObject var viewModel = ContentViewModel()
    
    var body: some View {
        NavigationView {
            List {
                ForEach(viewModel.data, id: \.self) { item in
                    Text(item)
                }
            }
            .navigationTitle("Pull to Refresh")
            .refreshable {
                viewModel.fetchData() // Refresh data on pull
            }
        }
    }
}

// Preview
struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }

Pull-to-refresh Combine SwiftUI Swift Data Binding Swift Programming