BackgroundRefreshSettingsViewModel.swift 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. // LoopFollow
  2. // BackgroundRefreshSettingsViewModel.swift
  3. import Combine
  4. import Foundation
  5. class BackgroundRefreshSettingsViewModel: ObservableObject {
  6. @Published var backgroundRefreshType: BackgroundRefreshType
  7. private var storage = Storage.shared
  8. private var cancellables = Set<AnyCancellable>()
  9. private var isInitialSetup = true // Tracks whether the value is being set initially
  10. init() {
  11. backgroundRefreshType = storage.backgroundRefreshType.value
  12. setupBindings()
  13. }
  14. private func setupBindings() {
  15. $backgroundRefreshType
  16. .dropFirst() // Ignore the initial emission during setup
  17. .sink { [weak self] newValue in
  18. guard let self = self else { return }
  19. self.handleBackgroundRefreshTypeChange(newValue)
  20. // Persist the change
  21. self.storage.backgroundRefreshType.value = newValue
  22. }
  23. .store(in: &cancellables)
  24. }
  25. private func handleBackgroundRefreshTypeChange(_ newValue: BackgroundRefreshType) {
  26. LogManager.shared.log(category: .general, message: "Background refresh type changed to: \(newValue.rawValue)")
  27. // Touch BLEManager only when switching to a Bluetooth mode (the user is
  28. // opting in, so the permission prompt belongs here) or when it's already
  29. // running and needs to be torn down. Switching between non-BLE modes must
  30. // not initialize Bluetooth — that would prompt without cause.
  31. if newValue.isBluetooth || BLEManager.isInitialized {
  32. BLEManager.shared.disconnect()
  33. }
  34. }
  35. }