2021-01-23 03:48:33 +00:00
|
|
|
// Copyright © 2020 Metabolist. All rights reserved.
|
|
|
|
|
|
|
|
import Combine
|
|
|
|
import Foundation
|
|
|
|
import ServiceLayer
|
|
|
|
|
|
|
|
public final class SearchViewModel: CollectionItemsViewModel {
|
|
|
|
@Published public var query = ""
|
2021-01-25 07:42:39 +00:00
|
|
|
@Published public var scope = SearchScope.all
|
2021-01-23 03:48:33 +00:00
|
|
|
|
|
|
|
private let searchService: SearchService
|
|
|
|
private var cancellables = Set<AnyCancellable>()
|
|
|
|
|
2021-01-26 00:06:35 +00:00
|
|
|
public init(searchService: SearchService, identityContext: IdentityContext) {
|
2021-01-23 03:48:33 +00:00
|
|
|
self.searchService = searchService
|
|
|
|
|
2021-01-26 00:06:35 +00:00
|
|
|
super.init(collectionService: searchService, identityContext: identityContext)
|
2021-01-23 03:48:33 +00:00
|
|
|
|
2021-01-25 02:10:41 +00:00
|
|
|
$query.removeDuplicates()
|
2021-02-07 01:20:15 +00:00
|
|
|
.debounce(for: .seconds(Self.debounceInterval), scheduler: DispatchQueue.global())
|
2021-01-25 02:10:41 +00:00
|
|
|
.combineLatest($scope.removeDuplicates())
|
|
|
|
.sink { [weak self] in
|
|
|
|
self?.request(
|
|
|
|
maxId: nil,
|
|
|
|
minId: nil,
|
|
|
|
search: .init(query: $0, type: $1.type, limit: $1.limit))
|
|
|
|
}
|
2021-01-23 03:48:33 +00:00
|
|
|
.store(in: &cancellables)
|
|
|
|
}
|
2021-01-24 22:14:35 +00:00
|
|
|
|
2021-01-25 02:10:41 +00:00
|
|
|
public override func requestNextPage(fromIndexPath indexPath: IndexPath) {
|
|
|
|
guard scope != .all else { return }
|
|
|
|
|
|
|
|
request(
|
|
|
|
maxId: nil,
|
|
|
|
minId: nil,
|
|
|
|
search: .init(query: query, type: scope.type, offset: indexPath.item + 1))
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-01-23 03:48:33 +00:00
|
|
|
private extension SearchViewModel {
|
2021-02-07 01:20:15 +00:00
|
|
|
static let debounceInterval: TimeInterval = 0.25
|
2021-01-25 02:10:41 +00:00
|
|
|
}
|
|
|
|
|
2021-01-25 07:42:39 +00:00
|
|
|
private extension SearchScope {
|
2021-01-25 02:10:41 +00:00
|
|
|
var type: Search.SearchType? {
|
|
|
|
switch self {
|
|
|
|
case .all:
|
|
|
|
return nil
|
|
|
|
case .accounts:
|
|
|
|
return .accounts
|
|
|
|
case .statuses:
|
|
|
|
return .statuses
|
|
|
|
case .tags:
|
|
|
|
return .hashtags
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
var limit: Int? {
|
|
|
|
switch self {
|
|
|
|
case .all:
|
|
|
|
return 5
|
|
|
|
default:
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
}
|
2021-01-23 03:48:33 +00:00
|
|
|
}
|