How do I support offline mode gracefully in Combine with Swift?

To gracefully support offline mode in a Swift application using Combine, you can leverage the built-in features of Combine to handle network requests while also maintaining a local data source. This allows your application to function smoothly even when there is no internet connection. The key is to use a combination of `CurrentValueSubject`, `Publishers`, and `sink` to manage and bind your data effectively.

Example Implementation

import Combine import Foundation class DataService { private var cancellables = Set() private var onlineDataSubject = CurrentValueSubject<[String], Never>([]) private var offlineData: [String] = [] private let isConnected = CurrentValueSubject(true) init() { setupNetworkMonitoring() } func fetchData() { isConnected .combineLatest(onlineDataSubject) .map { isConnected, onlineData in isConnected ? onlineData : self.offlineData } .sink(receiveValue: { data in print("Current Data: \(data)") }) .store(in: &cancellables) // Simulated network fetch fetchOnlineData() } private func setupNetworkMonitoring() { // Simulated network monitoring // In a real application, you would use a network monitoring library DispatchQueue.main.asyncAfter(deadline: .now() + 5) { self.isConnected.send(false) // Simulate Internet Disconnection } DispatchQueue.main.asyncAfter(deadline: .now() + 10) { self.isConnected.send(true) // Simulate Internet Reconnection } } private func fetchOnlineData() { // Simulate a network fetch and updating onlineDataSubject DispatchQueue.global().asyncAfter(deadline: .now() + 2) { let fetchedData = ["Data 1", "Data 2", "Data 3"] self.onlineDataSubject.send(fetchedData) self.offlineData = fetchedData // Store for offline use } } } // Usage Example let dataService = DataService() dataService.fetchData()

Offline Mode Combine Framework Swift Data Service