metatext/ViewModels/Sources/ViewModels/AccountStatusesViewModel.swift

78 lines
2.8 KiB
Swift
Raw Normal View History

2020-09-18 00:16:41 +00:00
// Copyright © 2020 Metabolist. All rights reserved.
import Combine
import Foundation
import Mastodon
import ServiceLayer
public class AccountStatusesViewModel: StatusListViewModel {
2020-09-26 07:13:50 +00:00
@Published public private(set) var accountViewModel: AccountViewModel?
2020-09-22 06:53:11 +00:00
@Published public var collection = AccountStatusCollection.statuses
2020-09-18 00:16:41 +00:00
private let accountStatusesService: AccountStatusesService
private var cancellables = Set<AnyCancellable>()
init(accountStatusesService: AccountStatusesService) {
self.accountStatusesService = accountStatusesService
2020-09-22 06:53:11 +00:00
let collectionSubject = CurrentValueSubject<AccountStatusCollection, Never>(.statuses)
2020-09-18 00:16:41 +00:00
super.init(
statusListService: accountStatusesService.statusListService(
2020-09-22 06:53:11 +00:00
collectionPublisher: collectionSubject))
$collection.sink(receiveValue: collectionSubject.send).store(in: &cancellables)
accountStatusesService.accountService
2020-09-26 07:13:50 +00:00
.map(AccountViewModel.init(accountService:))
2020-09-22 06:53:11 +00:00
.assignErrorsToAlertItem(to: \.alertItem, on: self)
2020-09-26 07:13:50 +00:00
.assign(to: &$accountViewModel)
2020-09-18 00:16:41 +00:00
}
2020-09-27 01:23:56 +00:00
public override var collectionItems: AnyPublisher<[[CollectionItem]], Never> {
// The pinned key is added to the info of collection items in the first section
// so a diffable data source can potentially render it in both sections
super.collectionItems
.map {
$0.enumerated().map {
$0 == 0 ? $1.map { .init(id: $0.id, kind: $0.kind, info: [.pinned: true]) } : $1
}
}
.eraseToAnyPublisher()
}
2020-09-26 07:45:39 +00:00
public override var navigationEvents: AnyPublisher<NavigationEvent, Never> {
$accountViewModel.compactMap { $0 }
.flatMap(\.events)
.flatMap { $0 }
.map(NavigationEvent.init)
.compactMap { $0 }
.assignErrorsToAlertItem(to: \.alertItem, on: self)
.merge(with: super.navigationEvents)
.eraseToAnyPublisher()
}
2020-09-18 00:16:41 +00:00
public override func request(maxID: String? = nil, minID: String? = nil) {
if case .statuses = collection, maxID == nil {
accountStatusesService.fetchPinnedStatuses()
.assignErrorsToAlertItem(to: \.alertItem, on: self)
.sink { _ in }
.store(in: &cancellables)
}
super.request(maxID: maxID, minID: minID)
}
2020-09-23 01:43:06 +00:00
public override var title: AnyPublisher<String?, Never> {
2020-09-26 07:13:50 +00:00
$accountViewModel.map { $0?.accountName }.eraseToAnyPublisher()
2020-09-23 01:43:06 +00:00
}
2020-09-18 00:16:41 +00:00
}
2020-09-22 06:53:11 +00:00
public extension AccountStatusesViewModel {
func fetchAccount() {
accountStatusesService.fetchAccount()
.assignErrorsToAlertItem(to: \.alertItem, on: self)
.sink { _ in }
.store(in: &cancellables)
}
}