Last active
July 12, 2020 16:45
-
-
Save ryotapoi/5b844e8b515124d2e59a0df77b990bfd to your computer and use it in GitHub Desktop.
CurrentValueSubjectを変更するとUserDefaultsにも保存されるサンプル
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import UIKit | |
import Combine | |
// これだけでは使いにくい。 | |
// * 色々な型への対応 | |
// * Property WrapperのprojectedValueとしてCurrentValueSubjectを返す | |
// とすれば使いやすくなるはず。 | |
class Box { | |
var cancelable: AnyCancellable? | |
} | |
func userDefaultSubject(key: String, default defaultValue: Int) -> CurrentValueSubject<Int, Never> { | |
let initialValue: Int | |
if let _ = UserDefaults.standard.object(forKey: key) { | |
initialValue = UserDefaults.standard.integer(forKey: key) | |
} else { | |
initialValue = defaultValue | |
} | |
let cvs = CurrentValueSubject<Int, Never>(initialValue) | |
let box = Box() | |
let cancelable = cvs.sink { [box] (value) in | |
_ = box // boxをキャプチャして、警告を消すために使う | |
UserDefaults.standard.set(value, forKey: key) | |
} | |
box.cancelable = cancelable | |
return cvs | |
} | |
UserDefaults.standard.removePersistentDomain(forName: Bundle.main.bundleIdentifier!) | |
let age = userDefaultSubject(key: "key", default: 0) | |
age.sink { (value) in | |
print(value) | |
} | |
age.value = 100 | |
age.value | |
UserDefaults.standard.integer(forKey: "key") | |
age.value = 200 | |
age.value | |
UserDefaults.standard.integer(forKey: "key") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment