fix: search history not isolate issue

This commit is contained in:
CMK 2021-07-22 14:13:49 +08:00
parent f4056f1049
commit 39cdc01317
3 changed files with 45 additions and 0 deletions

View File

@ -99,3 +99,20 @@ extension SearchHistory: Managed {
return [NSSortDescriptor(keyPath: \SearchHistory.updatedAt, ascending: false)]
}
}
extension SearchHistory {
static func predicate(domain: String) -> NSPredicate {
return NSPredicate(format: "%K == %@", #keyPath(SearchHistory.domain), domain)
}
static func predicate(userID: String) -> NSPredicate {
return NSPredicate(format: "%K == %@", #keyPath(SearchHistory.userID), userID)
}
public static func predicate(domain: String, userID: String) -> NSPredicate {
return NSCompoundPredicate(andPredicateWithSubpredicates: [
predicate(domain: domain),
predicate(userID: userID)
])
}
}

View File

@ -17,6 +17,8 @@ final class SearchHistoryFetchedResultController: NSObject {
var disposeBag = Set<AnyCancellable>()
let fetchedResultsController: NSFetchedResultsController<SearchHistory>
let domain = CurrentValueSubject<String?, Never>(nil)
let userID = CurrentValueSubject<Mastodon.Entity.Status.ID?, Never>(nil)
// output
let objectIDs = CurrentValueSubject<[NSManagedObjectID], Never>([])
@ -38,6 +40,23 @@ final class SearchHistoryFetchedResultController: NSObject {
super.init()
fetchedResultsController.delegate = self
Publishers.CombineLatest(
self.domain.removeDuplicates(),
self.userID.removeDuplicates()
)
.receive(on: DispatchQueue.main)
.sink { [weak self] domain, userID in
guard let self = self else { return }
let predicates = [SearchHistory.predicate(domain: domain ?? "", userID: userID ?? "")]
self.fetchedResultsController.fetchRequest.predicate = NSCompoundPredicate(andPredicateWithSubpredicates: predicates)
do {
try self.fetchedResultsController.performFetch()
} catch {
assertionFailure(error.localizedDescription)
}
}
.store(in: &disposeBag)
}
}

View File

@ -25,6 +25,15 @@ final class SearchHistoryViewModel {
self.context = context
self.searchHistoryFetchedResultController = SearchHistoryFetchedResultController(managedObjectContext: context.managedObjectContext)
context.authenticationService.activeMastodonAuthenticationBox
.receive(on: DispatchQueue.main)
.sink { [weak self] box in
guard let self = self else { return }
self.searchHistoryFetchedResultController.domain.value = box?.domain
self.searchHistoryFetchedResultController.userID.value = box?.userID
}
.store(in: &disposeBag)
// may block main queue by large dataset
searchHistoryFetchedResultController.objectIDs
.removeDuplicates()