metatext-app-ios-iphone-ipad/View Models/NotificationTypesPreference...

47 lines
1.5 KiB
Swift
Raw Normal View History

2020-08-14 23:41:55 +02:00
// Copyright © 2020 Metabolist. All rights reserved.
import Foundation
import Combine
2020-08-31 01:33:11 +02:00
import Mastodon
2020-08-31 12:21:01 +02:00
import Services
2020-08-14 23:41:55 +02:00
class NotificationTypesPreferencesViewModel: ObservableObject {
@Published var pushSubscriptionAlerts: PushSubscription.Alerts
@Published var alertItem: AlertItem?
private let identityService: IdentityService
private var cancellables = Set<AnyCancellable>()
init(identityService: IdentityService) {
self.identityService = identityService
pushSubscriptionAlerts = identityService.identity.pushSubscriptionAlerts
identityService.$identity
.map(\.pushSubscriptionAlerts)
.dropFirst()
.removeDuplicates()
.assign(to: &$pushSubscriptionAlerts)
$pushSubscriptionAlerts
.dropFirst()
.removeDuplicates()
2020-08-24 07:15:46 +02:00
.sink { [weak self] in self?.update(alerts: $0) }
2020-08-14 23:41:55 +02:00
.store(in: &cancellables)
}
}
private extension NotificationTypesPreferencesViewModel {
func update(alerts: PushSubscription.Alerts) {
guard alerts != identityService.identity.pushSubscriptionAlerts else { return }
identityService.updatePushSubscription(alerts: alerts)
.sink { [weak self] in
guard let self = self, case let .failure(error) = $0 else { return }
self.alertItem = AlertItem(error: error)
self.pushSubscriptionAlerts = self.identityService.identity.pushSubscriptionAlerts
2020-08-26 11:19:38 +02:00
} receiveValue: { _ in }
2020-08-14 23:41:55 +02:00
.store(in: &cancellables)
}
}