-
-
Notifications
You must be signed in to change notification settings - Fork 38
Expand file tree
/
Copy pathArticleViewModel.swift
More file actions
46 lines (39 loc) · 1.57 KB
/
ArticleViewModel.swift
File metadata and controls
46 lines (39 loc) · 1.57 KB
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
//
// NewsFeedViewModel.swift
// NYTimes
//
// Created by Waseem Akram on 29/07/20.
// Copyright © 2020 Waseem Akram. All rights reserved.
//
import Foundation
import Combine
class ArticleViewModel: ObservableObject {
var htmlScrapUtlity = HTMLScraperUtility()
@Published var articles = [Article]()
@Published var isArticlesLoading = false
@Published var searchText = ""
var cancellableTask: AnyCancellable? = nil
var searchResults : [Article] {
if searchText.isEmpty {
return articles
} else {
return articles.filter { $0.title.lowercased().contains(searchText.lowercased()) || $0.subtitle.lowercased().contains(searchText.lowercased()) || $0.author.lowercased().contains(searchText.lowercased()) }
}
}
func loadArticles(for category: Category) {
guard let url = URL(string: category.url) else { return }
self.isArticlesLoading = true
self.cancellableTask?.cancel() //cancel last subscription to prevent race condition
self.cancellableTask = URLSession.shared.dataTaskPublisher(for: url)
.map(\.data) //extract Data() from tuple
.flatMap(htmlScrapUtlity.scrapArticle(from:)) //send data to scrap function that will return article objects (array)
.sink { (completion) in
self.isArticlesLoading = false //once we got articles, close the loader
} receiveValue: { [unowned self] (articles) in
self.articles = articles
}
}
deinit {
cancellableTask = nil
}
}