Skip to content

Instantly share code, notes, and snippets.

@anupamchugh
Last active February 20, 2020 12:34
Show Gist options
  • Save anupamchugh/875878c140f852590a1292f001304d24 to your computer and use it in GitHub Desktop.
Save anupamchugh/875878c140f852590a1292f001304d24 to your computer and use it in GitHub Desktop.
class HNCommentFeed : ObservableObject{
let nlTagger = NLTagger(tagSchemes: [.sentimentScore])
let didChange = PassthroughSubject<Void, Never>()
var cancellable : Set<AnyCancellable> = Set()
@Published var sentimentAvg : String = ""
var comments = [CommentItem](){
didSet {
var sumSentiments : Float = 0.0
for item in comments{
let floatValue = (item.sentimentScore as NSString).floatValue
sumSentiments += floatValue
}
let ave = (sumSentiments) / Float(comments.count)
sentimentAvg = String(format: "%.2f", ave)
didChange.send()
}
}
private var commentIds = [Int]() {
didSet {
fetchComments(ids: commentIds.prefix(10))
}
}
func fetchComments<S>(ids: S) where S: Sequence, S.Element == Int{
Publishers.MergeMany(ids.map{FetchComment(id: $0, nlTagger: nlTagger)})
.collect()
.receive(on: DispatchQueue.main)
.sink(receiveCompletion: {
if case let .failure(error) = $0 {
print(error)
}
}, receiveValue: {
self.comments = self.comments + $0
})
.store(in: &cancellable)
}
func getIds(ids: [Int]){
self.commentIds = ids
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment