Bug fix: we weren't saving the user's preferred currency type (bitcoin or fiat)
import Foundation
import PhoenixShared
import Combine
+import UIKit
/// An ObservableObject that monitors the currently stored values in UserDefaults.
/// Available as an EnvironmentObject:
@@ -18,6 +19,9 @@ class CurrencyPrefs: ObservableObject {
private var cancellables = Set<AnyCancellable>()
private var unsubscribe: (() -> Void)? = nil
+ private var currencyTypeTimer: Timer? = nil
+ private var currencyTypeNeedsSave: Bool = false
+
init() {
currencyType = Prefs.shared.currencyType
fiatCurrency = Prefs.shared.fiatCurrency
@@ -44,6 +48,11 @@ class CurrencyPrefs: ObservableObject {
self?.fiatExchangeRates = event.rates
}
}
+
+ let nc = NotificationCenter.default
+ nc.publisher(for: UIApplication.willResignActiveNotification).sink {[weak self] _ in
+ self?.saveCurrencyTypeIfNeeded()
+ }.store(in: &cancellables)
}
private init(
@@ -62,15 +71,24 @@ class CurrencyPrefs: ObservableObject {
deinit {
unsubscribe?()
+ currencyTypeTimer?.invalidate()
}
func toggleCurrencyType() -> Void {
- if currencyType == .fiat {
- currencyType = .bitcoin
- } else {
- currencyType = .fiat
- }
+ assert(Thread.isMainThread, "This function is restricted to the main-thread")
+
+ // I don't really want to save the currencyType to disk everytime the user changes it.
+ // Because users tend to toggle back and forth often.
+ // So we're using a timer, plus a listener on applicationWillResignActive.
+
+ currencyType = (currencyType == .fiat) ? .bitcoin : .fiat
+ currencyTypeNeedsSave = true
+
+ currencyTypeTimer?.invalidate()
+ currencyTypeTimer = Timer.scheduledTimer(withTimeInterval: 10.0, repeats: false, block: {[weak self] _ in
+ self?.saveCurrencyTypeIfNeeded()
+ })
}
/// Returns the exchangeRate for the currently set fiatCurrency.
@@ -89,6 +107,18 @@ class CurrencyPrefs: ObservableObject {
}
}
+ private func saveCurrencyTypeIfNeeded() -> Void {
+
+ if currencyTypeNeedsSave {
+ currencyTypeNeedsSave = false
+
+ Prefs.shared.currencyType = self.currencyType
+
+ currencyTypeTimer?.invalidate()
+ currencyTypeTimer = nil
+ }
+ }
+
static func mockUSD() -> CurrencyPrefs {
return CurrencyPrefs(currencyType: .bitcoin, fiatCurrency: .usd, bitcoinUnit: .satoshi, exchangeRate: 20_000.00)
}
