2021-01-23 04:48:33 +01:00
|
|
|
// Copyright © 2020 Metabolist. All rights reserved.
|
|
|
|
|
|
|
|
import Combine
|
|
|
|
import Foundation
|
|
|
|
import ServiceLayer
|
|
|
|
|
|
|
|
public final class SearchViewModel: CollectionItemsViewModel {
|
|
|
|
@Published public var query = ""
|
|
|
|
|
|
|
|
private let searchService: SearchService
|
|
|
|
private var cancellables = Set<AnyCancellable>()
|
|
|
|
|
|
|
|
public init(searchService: SearchService, identification: Identification) {
|
|
|
|
self.searchService = searchService
|
|
|
|
|
|
|
|
super.init(collectionService: searchService, identification: identification)
|
|
|
|
|
2021-01-24 23:14:35 +01:00
|
|
|
$query.throttle(for: .seconds(Self.throttleInterval), scheduler: DispatchQueue.global(), latest: true)
|
2021-01-23 04:48:33 +01:00
|
|
|
.sink { [weak self] in self?.request(maxId: nil, minId: nil, search: .init(query: $0, limit: Self.limit)) }
|
|
|
|
.store(in: &cancellables)
|
|
|
|
}
|
2021-01-24 23:14:35 +01:00
|
|
|
|
|
|
|
public override var updates: AnyPublisher<CollectionUpdate, Never> {
|
|
|
|
// Since results are processed through the DB to determine CW expansion state etc they can arrive erratically
|
|
|
|
super.updates
|
|
|
|
.throttle(for: .seconds(Self.throttleInterval), scheduler: DispatchQueue.global(), latest: true)
|
|
|
|
.eraseToAnyPublisher()
|
|
|
|
}
|
2021-01-23 04:48:33 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
private extension SearchViewModel {
|
2021-01-24 23:14:35 +01:00
|
|
|
static let throttleInterval: TimeInterval = 0.5
|
2021-01-23 04:48:33 +01:00
|
|
|
static let limit = 5
|
|
|
|
}
|