RemoteConfigValueObservable.swift 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. /*
  2. * Copyright 2022 Google LLC
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. import SwiftUI
  17. import FirebaseRemoteConfig
  18. extension Notification.Name {
  19. static let onRemoteConfigChanged = Notification.Name("FIRRemoteConfigChangeNotification")
  20. }
  21. @available(iOS 14.0, macOS 11.0, macCatalyst 14.0, tvOS 14.0, watchOS 7.0, *)
  22. internal class RemoteConfigValueObservable<T: Decodable>: ObservableObject {
  23. @Published var configValue: T
  24. private let key: String
  25. private let remoteConfig: RemoteConfig
  26. private let fallbackValue : T
  27. private var registration: FIRConfigUpdateListenerRegistration?
  28. init(key: String, fallbackValue: T) {
  29. self.key = key
  30. self.remoteConfig = RemoteConfig.remoteConfig()
  31. self.fallbackValue = fallbackValue
  32. // Initialize with fallback value
  33. self.configValue = fallbackValue
  34. // Check cached remote config value
  35. do {
  36. let configValue : RemoteConfigValue = self.remoteConfig[key]
  37. if configValue.source == .remote || configValue.source == .default {
  38. self.configValue = try self.remoteConfig[key].decoded()
  39. } else {
  40. self.configValue = fallbackValue
  41. }
  42. } catch {
  43. self.configValue = fallbackValue
  44. }
  45. NotificationCenter.default.addObserver(self, selector: #selector(configDidActivated), name: .onRemoteConfigChanged, object: nil)
  46. }
  47. @objc func configDidActivated() {
  48. do {
  49. let configValue : RemoteConfigValue = self.remoteConfig[self.key]
  50. if configValue.source == .remote {
  51. self.configValue = try self.remoteConfig[self.key].decoded()
  52. }
  53. } catch {
  54. }
  55. }
  56. deinit {
  57. self.registration?.remove()
  58. }
  59. }