forked from Dimillian/RedditOS
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSearchSubredditsViewModel.swift
51 lines (45 loc) · 1.56 KB
/
SearchSubredditsViewModel.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
//
// SearchSubredditsViewModel.swift
// RedditOs
//
// Created by Thomas Ricouard on 09/07/2020.
//
import Foundation
import SwiftUI
import Combine
import Backend
class SearchSubredditsViewModel: ObservableObject {
@Published var searchText = ""
@Published var results: [Subreddit]?
@Published var isLoading = false
private var searchCancellable: AnyCancellable?
private var apiPublisher: AnyPublisher<SubredditResponse, Never>?
private var apiCancellable: AnyCancellable?
init() {
searchCancellable = $searchText
.subscribe(on: DispatchQueue.global())
.debounce(for: .milliseconds(500), scheduler: DispatchQueue.main)
.removeDuplicates()
.filter { !$0.isEmpty }
.receive(on: DispatchQueue.main)
.sink(receiveValue: { [weak self] text in
self?.isLoading = true
self?.search(with: text)
})
}
private func search(with text: String) {
apiCancellable?.cancel()
let param = ["query": text]
apiPublisher = API.shared.request(endpoint: .searchSubreddit, httpMethod: "POST", params: param)
.subscribe(on: DispatchQueue.global())
.replaceError(with: SubredditResponse())
.eraseToAnyPublisher()
apiCancellable = apiPublisher?
.receive(on: DispatchQueue.main)
.map{ $0.subreddits }
.sink{ [weak self] results in
self?.isLoading = false
self?.results = results
}
}
}