-
Notifications
You must be signed in to change notification settings - Fork 0
/
SongListViewModel.swift
60 lines (50 loc) · 1.37 KB
/
SongListViewModel.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
58
59
60
//
// SongListViewModel.swift
// Busca tu musica
//
// Created by Sebastian Gomez on 21/10/2021.
//
import Combine
import Foundation
import SwiftUI
class SongListViewModel: ObservableObject {
@Published var searchTerm: String = ""
@Published public private(set) var songs: [SongViewModel] = []
private let dataModel: DataModel = DataModel()
private let artworkLoader: ArtworkLoader = ArtworkLoader()
private var disposables = Set<AnyCancellable>()
init() {
$searchTerm
.sink(receiveValue: loadSongs(searchTerm:))
.store(in: &disposables)
}
private func loadSongs(searchTerm: String) {
songs.removeAll()
artworkLoader.reset()
dataModel.loadSongs(searchTerm: searchTerm) { songs in
songs.forEach { self.appendSong(song: $0) }
}
}
private func appendSong(song: Song) {
let songViewModel = SongViewModel(song: song)
DispatchQueue.main.async {
self.songs.append(songViewModel)
}
artworkLoader.loadArtwork(forSong: song) { image in
DispatchQueue.main.async {
songViewModel.artwork = image
}
}
}
}
class SongViewModel: Identifiable, ObservableObject {
let id: Int
let trackName: String
let artistName: String
@Published var artwork: Image?
init(song: Song) {
self.id = song.id
self.trackName = song.trackName
self.artistName = song.artistName
}
}