-
Notifications
You must be signed in to change notification settings - Fork 0
/
Storage.swift
55 lines (45 loc) · 1.57 KB
/
Storage.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
import Combine
import Foundation
import SwiftData
class Storage {
static let `default` = Storage()
private let modelContainer: ModelContainer?
private let modelContext: ModelContext?
private init() {
if let modelContainer = try? ModelContainer(
for: ComicModel.self
) {
self.modelContainer = modelContainer
modelContext = ModelContext(modelContainer)
} else {
modelContainer = nil
modelContext = nil
}
}
func insert(_ comicModel: ComicModel) {
let id = comicModel.id
try? modelContext?.delete(
model: ComicModel.self,
where: #Predicate<ComicModel> { $0.id == id }
)
modelContext?.insert(comicModel)
try? modelContext?.save()
}
func delete(_ comicModel: ComicModel) {
modelContext?.delete(comicModel)
try? modelContext?.save()
}
func isMarkedAsReadPublisher(id: Int?) -> AnyPublisher<Bool, Never> {
guard let id else {
return Just(false).eraseToAnyPublisher()
}
let predicate = #Predicate<ComicModel> { $0.id == id && $0.isRead == true }
let descriptor = FetchDescriptor<ComicModel>(predicate: predicate)
let result = CurrentValueSubject<Bool?, Never>(nil)
DispatchQueue.global(qos: .default).async { [weak self] in
let isMarkedAsRead = ((try? self?.modelContext?.fetch(descriptor).count) ?? 0) > 0
result.send(isMarkedAsRead)
}
return result.compactMap { $0 }.eraseToAnyPublisher()
}
}