Skip to content

Instantly share code, notes, and snippets.

@woodycatliu
Created February 11, 2022 06:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save woodycatliu/4c010172819833c63ff22ec9a743a5d3 to your computer and use it in GitHub Desktop.
Save woodycatliu/4c010172819833c63ff22ec9a743a5d3 to your computer and use it in GitHub Desktop.
Easy way to safe in userDefault within Combine flow

Easy way to safe in userDefault within Combine flow

function name: safeInUserDefaultFirst Encode Publisher Ouput, safe in userDefault within key and then continuous the flow

function name: safeInUserDefault Encode Publisher Ouput, safe in userDefault within key and then finishes the flow

import Combine
extension Publisher where Self.Output: Encodable {
func safeInUserDefaultFirst(_ key: String) -> AnyPublisher<Self.Output, Self.Failure> {
return flatMap { (output)-> Just<Self.Output> in
let data = try? JSONEncoder().encode(output)
UserDefaults.standard.set(data, forKey: key)
return Just(output)
}.eraseToAnyPublisher()
}
}
extension Publishers.Decode {
func safeInUserDefaultFirst(_ key: String) -> AnyPublisher<Self.Output, Self.Failure> where Self.Output: Codable {
return flatMap { (output)-> Just<Self.Output> in
let data = try? JSONEncoder().encode(output)
UserDefaults.standard.set(data, forKey: key)
return Just(output)
}.eraseToAnyPublisher()
}
}
extension Publisher where Self.Output: Encodable {
func safeInUserDefault(_ key: String)-> AnyCancellable {
return sink(receiveCompletion: { _ in }, receiveValue: {
let data = try? JSONEncoder().encode($0)
UserDefaults.standard.set(data, forKey: key)
})
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment