metatext-app-ios-iphone-ipad/ViewModels/Sources/ViewModels/ProfileViewModel.swift

73 lines
2.6 KiB
Swift
Raw Normal View History

2020-09-18 02:16:41 +02:00
// Copyright © 2020 Metabolist. All rights reserved.
import Combine
import Foundation
import Mastodon
import ServiceLayer
2020-09-27 04:03:53 +02:00
public class ProfileViewModel: StatusListViewModel {
2020-09-26 09:13:50 +02:00
@Published public private(set) var accountViewModel: AccountViewModel?
2020-09-27 04:03:53 +02:00
@Published public var collection = ProfileCollection.statuses
private let profileService: ProfileService
2020-09-18 02:16:41 +02:00
private var cancellables = Set<AnyCancellable>()
2020-09-27 04:03:53 +02:00
init(profileService: ProfileService) {
self.profileService = profileService
2020-09-18 02:16:41 +02:00
2020-09-27 04:03:53 +02:00
let collectionSubject = CurrentValueSubject<ProfileCollection, Never>(.statuses)
2020-09-18 02:16:41 +02:00
super.init(
2020-09-27 04:03:53 +02:00
statusListService: profileService.statusListService(
2020-09-22 08:53:11 +02:00
collectionPublisher: collectionSubject))
$collection.sink(receiveValue: collectionSubject.send).store(in: &cancellables)
2020-09-27 04:03:53 +02:00
profileService.accountService
2020-09-26 09:13:50 +02:00
.map(AccountViewModel.init(accountService:))
2020-09-22 08:53:11 +02:00
.assignErrorsToAlertItem(to: \.alertItem, on: self)
2020-09-26 09:13:50 +02:00
.assign(to: &$accountViewModel)
2020-09-18 02:16:41 +02:00
}
2020-09-27 03:23:56 +02: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 {
2020-09-28 22:52:46 +02:00
$0.enumerated().map { [weak self] in
if let self = self, self.collection == .statuses, $0 == 0 {
return $1.map { .init(id: $0.id, kind: $0.kind, info: [.pinned: true]) }
} else {
return $1
}
2020-09-27 03:23:56 +02:00
}
}
.eraseToAnyPublisher()
}
2020-09-26 09:45:39 +02: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 02:16:41 +02:00
public override func request(maxID: String? = nil, minID: String? = nil) {
if case .statuses = collection, maxID == nil {
2020-09-27 04:03:53 +02:00
profileService.fetchPinnedStatuses()
2020-09-18 02:16:41 +02:00
.assignErrorsToAlertItem(to: \.alertItem, on: self)
.sink { _ in }
.store(in: &cancellables)
}
super.request(maxID: maxID, minID: minID)
}
2020-09-23 03:43:06 +02:00
public override var title: AnyPublisher<String?, Never> {
2020-09-26 09:13:50 +02:00
$accountViewModel.map { $0?.accountName }.eraseToAnyPublisher()
2020-09-23 03:43:06 +02:00
}
2020-09-18 02:16:41 +02:00
}