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.
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()
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?