· 4 years ago · Aug 23, 2021, 03:54 PM
1import Foundation
2import Combine
3
4class MainContentHome:ObservableObject {
5
6 enum state {
7 case loading,idle,done,failed
8 }
9
10 @Published var State:state = .idle
11 @Published var MainContent = [BasicHome]()
12 private var myAPI = Api()
13 private var page = 1
14 private var cancellables = Set<AnyCancellable>()
15
16 init(){
17 fetchAPI()
18 }
19
20 func fetchAPI() {
21 //Idle is the 1st state, when the app loads, loading state is when we want to add more content to it
22 if self.State != .idle {
23 self.State = .loading
24 }
25 let path = {() -> URLComponents in
26 self.myAPI.link!.path = "/api/games"
27 self.myAPI.link!.queryItems = [
28 URLQueryItem(name: "key", value: self.myAPI.key),
29 URLQueryItem(name: "ordering", value: "updated"),
30 URLQueryItem(name: "page", value: String(page
31 ))
32 ]
33 return myAPI.link!
34 }()
35
36 let request = URLRequest(url: path.url!)
37 URLSession.shared.dataTaskPublisher(for: request)
38 .tryMap { $0.data }
39 .decode(type: HomeModelBasic.self, decoder: JSONDecoder())
40 .receive(on:RunLoop.main)
41 .sink {[weak self] complete in
42 print("fetching Main Content :\(complete) on page \(self!.page)")
43 self?.page+=1
44 } receiveValue: { [weak self] result in
45 self?.MainContent += result.results
46 self?.State = .loading
47 // Nanti mau naro jika full, state = .load tapi nanti dulu hehehe
48 }
49 .store(in: &cancellables)
50
51 }
52}