2020-08-07 10:14:14 +00:00
|
|
|
// Copyright © 2020 Metabolist. All rights reserved.
|
|
|
|
|
|
|
|
import Foundation
|
|
|
|
import Combine
|
|
|
|
|
2020-08-07 10:59:48 +00:00
|
|
|
class PostingReadingPreferencesViewModel: ObservableObject {
|
2020-08-07 10:14:14 +00:00
|
|
|
@Published var preferences: Identity.Preferences
|
|
|
|
@Published var alertItem: AlertItem?
|
|
|
|
let handle: String
|
|
|
|
|
2020-08-07 22:18:54 +00:00
|
|
|
private let identityRepository: IdentityRepository
|
2020-08-07 10:14:14 +00:00
|
|
|
private var cancellables = Set<AnyCancellable>()
|
|
|
|
|
2020-08-07 22:18:54 +00:00
|
|
|
init(identityRepository: IdentityRepository) {
|
|
|
|
self.identityRepository = identityRepository
|
|
|
|
preferences = identityRepository.identity.preferences
|
|
|
|
handle = identityRepository.identity.handle
|
2020-08-07 10:14:14 +00:00
|
|
|
|
2020-08-07 22:18:54 +00:00
|
|
|
identityRepository.$identity.map(\.preferences)
|
2020-08-07 10:14:14 +00:00
|
|
|
.dropFirst()
|
|
|
|
.removeDuplicates()
|
|
|
|
.handleEvents(receiveOutput: { [weak self] in
|
2020-08-07 10:59:48 +00:00
|
|
|
if $0.useServerPostingReadingPreferences {
|
2020-08-07 21:57:18 +00:00
|
|
|
self?.refreshServerPreferences()
|
2020-08-07 10:14:14 +00:00
|
|
|
}
|
|
|
|
})
|
|
|
|
.assign(to: &$preferences)
|
|
|
|
|
|
|
|
$preferences.dropFirst()
|
2020-08-07 22:18:54 +00:00
|
|
|
.flatMap(identityRepository.updatePreferences)
|
2020-08-07 10:14:14 +00:00
|
|
|
.assignErrorsToAlertItem(to: \.alertItem, on: self)
|
|
|
|
.sink(receiveValue: {})
|
|
|
|
.store(in: &cancellables)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-08-07 10:59:48 +00:00
|
|
|
extension PostingReadingPreferencesViewModel {
|
2020-08-07 21:57:18 +00:00
|
|
|
private func refreshServerPreferences() {
|
2020-08-07 22:18:54 +00:00
|
|
|
identityRepository.refreshServerPreferences()
|
2020-08-07 10:14:14 +00:00
|
|
|
.assignErrorsToAlertItem(to: \.alertItem, on: self)
|
|
|
|
.sink(receiveValue: {})
|
|
|
|
.store(in: &cancellables)
|
|
|
|
}
|
|
|
|
}
|