forked from Dimillian/RedditOS
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSubredditViewModel.swift
57 lines (49 loc) · 1.61 KB
/
SubredditViewModel.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
52
53
54
55
56
57
//
// SubredditViewModel.swift
// RedditOs
//
// Created by Thomas Ricouard on 09/07/2020.
//
import Foundation
import SwiftUI
import Combine
import Backend
class SubredditViewModel: ObservableObject {
enum SortOrder: String, CaseIterable {
case hot, new, top, rising
}
let name: String
private var listingPublisher: AnyPublisher<ListingResponse, Never>?
private var listingCancellable: AnyCancellable?
@Published var listings: [Listing]?
@Published var sortOrder = SortOrder.hot {
didSet {
listings = nil
fetchListings()
}
}
init(name: String) {
self.name = name
}
func fetchListings() {
var params: [String: String] = [:]
if let last = listings?.last {
params["after"] = "t3_\(last.id)"
}
listingPublisher = API.shared.request(endpoint: .subreddit(name: name, sort: sortOrder.rawValue),
params: params)
.subscribe(on: DispatchQueue.global())
.replaceError(with: ListingResponse(error: "error"))
.eraseToAnyPublisher()
listingCancellable = listingPublisher?
.receive(on: DispatchQueue.main)
.map{ $0.data?.children.map{ $0.data }}
.sink{ [weak self] listings in
if params["after"] != nil, let listings = listings {
self?.listings?.append(contentsOf: listings)
} else if params["after"] == nil {
self?.listings = listings
}
}
}
}