2021-01-28 09:10:30 +01:00
|
|
|
//
|
|
|
|
// PublicTimelineViewModel+Diffable.swift
|
|
|
|
// Mastodon
|
|
|
|
//
|
|
|
|
// Created by sxiaojian on 2021/1/27.
|
|
|
|
//
|
|
|
|
|
|
|
|
import CoreData
|
|
|
|
import CoreDataStack
|
2021-02-02 12:04:24 +01:00
|
|
|
import os.log
|
|
|
|
import UIKit
|
2021-01-28 09:10:30 +01:00
|
|
|
|
|
|
|
extension PublicTimelineViewModel {
|
|
|
|
func setupDiffableDataSource(
|
|
|
|
for tableView: UITableView,
|
|
|
|
dependency: NeedsDependency,
|
|
|
|
timelinePostTableViewCellDelegate: TimelinePostTableViewCellDelegate
|
|
|
|
) {
|
|
|
|
let timestampUpdatePublisher = Timer.publish(every: 1.0, on: .main, in: .common)
|
|
|
|
.autoconnect()
|
|
|
|
.share()
|
|
|
|
.eraseToAnyPublisher()
|
2021-02-02 12:04:24 +01:00
|
|
|
|
2021-01-28 09:10:30 +01:00
|
|
|
diffableDataSource = TimelineSection.tableViewDiffableDataSource(
|
|
|
|
for: tableView,
|
|
|
|
dependency: dependency,
|
|
|
|
managedObjectContext: fetchedResultsController.managedObjectContext,
|
|
|
|
timestampUpdatePublisher: timestampUpdatePublisher,
|
2021-02-02 12:04:24 +01:00
|
|
|
timelinePostTableViewCellDelegate: timelinePostTableViewCellDelegate
|
|
|
|
)
|
2021-01-28 09:10:30 +01:00
|
|
|
items.value = []
|
2021-02-04 07:45:44 +01:00
|
|
|
stateMachine.enter(PublicTimelineViewModel.State.Loading.self)
|
2021-01-28 09:10:30 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// MARK: - NSFetchedResultsControllerDelegate
|
2021-02-02 12:04:24 +01:00
|
|
|
|
2021-01-28 09:10:30 +01:00
|
|
|
extension PublicTimelineViewModel: NSFetchedResultsControllerDelegate {
|
|
|
|
func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChangeContentWith snapshot: NSDiffableDataSourceSnapshotReference) {
|
2021-02-02 12:04:24 +01:00
|
|
|
os_log("%{public}s[%{public}ld], %{public}s", (#file as NSString).lastPathComponent, #line, #function)
|
|
|
|
|
2021-02-01 11:06:29 +01:00
|
|
|
let indexes = tootIDs.value
|
2021-01-28 09:10:30 +01:00
|
|
|
let toots = fetchedResultsController.fetchedObjects ?? []
|
2021-02-04 04:12:17 +01:00
|
|
|
guard toots.count == indexes.count else { return }
|
2021-01-28 09:10:30 +01:00
|
|
|
let items: [Item] = toots
|
|
|
|
.compactMap { toot -> (Int, Toot)? in
|
|
|
|
guard toot.deletedAt == nil else { return nil }
|
|
|
|
return indexes.firstIndex(of: toot.id).map { index in (index, toot) }
|
|
|
|
}
|
|
|
|
.sorted { $0.0 < $1.0 }
|
|
|
|
.map { Item.toot(objectID: $0.1.objectID) }
|
|
|
|
self.items.value = items
|
|
|
|
}
|
|
|
|
}
|