metatext/Shared/View Models/StatusesViewModel.swift

57 lines
2.1 KiB
Swift
Raw Normal View History

2020-08-18 05:13:37 +00:00
// Copyright © 2020 Metabolist. All rights reserved.
import Foundation
import Combine
class StatusesViewModel: ObservableObject {
2020-08-19 22:16:03 +00:00
@Published private(set) var statusSections = [[Status]]()
2020-08-18 05:13:37 +00:00
@Published var alertItem: AlertItem?
2020-08-19 22:16:03 +00:00
@Published private(set) var loading = false
let scrollToStatusID: AnyPublisher<String, Never>
2020-08-18 05:13:37 +00:00
private let statusListService: StatusListService
2020-08-19 22:16:03 +00:00
private let scrollToStatusIDInput = PassthroughSubject<String, Never>()
private var hasScrolledToParentAfterContextLoad = false
2020-08-18 05:13:37 +00:00
private var cancellables = Set<AnyCancellable>()
init(statusListService: StatusListService) {
self.statusListService = statusListService
2020-08-19 22:16:03 +00:00
scrollToStatusID = scrollToStatusIDInput.eraseToAnyPublisher()
2020-08-18 05:13:37 +00:00
statusListService.statusSections
.assignErrorsToAlertItem(to: \.alertItem, on: self)
.assign(to: &$statusSections)
2020-08-19 22:16:03 +00:00
$statusSections
.sink { [weak self] in
guard let self = self else { return }
if
let contextParent = self.contextParent,
!($0.first ?? []).isEmpty || !(($0.last ?? []).isEmpty),
!self.hasScrolledToParentAfterContextLoad {
self.hasScrolledToParentAfterContextLoad = true
self.scrollToStatusIDInput.send(contextParent.id)
}
}
.store(in: &cancellables)
2020-08-18 05:13:37 +00:00
}
}
extension StatusesViewModel {
2020-08-19 22:16:03 +00:00
var contextParent: Status? { statusListService.contextParent }
2020-08-18 05:13:37 +00:00
func request(maxID: String? = nil, minID: String? = nil) {
statusListService.request(maxID: maxID, minID: minID)
.assignErrorsToAlertItem(to: \.alertItem, on: self)
2020-08-19 22:16:03 +00:00
.handleEvents(
receiveSubscription: { [weak self] _ in self?.loading = true },
receiveCompletion: { [weak self] _ in self?.loading = false })
2020-08-18 05:13:37 +00:00
.sink {}
.store(in: &cancellables)
}
2020-08-19 22:16:03 +00:00
func contextViewModel(status: Status) -> StatusesViewModel {
StatusesViewModel(statusListService: statusListService.contextService(status: status))
}
2020-08-18 05:13:37 +00:00
}