-
Notifications
You must be signed in to change notification settings - Fork 0
/
BookStorage.swift
61 lines (51 loc) · 1.51 KB
/
BookStorage.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
61
import Combine
import CoreData
import CombineCoreData
final class BookStorage {
let backgroundContex: NSManagedObjectContext
init(backgroundContex: NSManagedObjectContext) {
self.backgroundContex = backgroundContex
}
}
// MARK: - Save books
extension BookStorage {
func saveBooks(names: [String], completion: @escaping (Error?) -> Void) {
backgroundContex.perform {
for name in names {
let book = Book(context: self.backgroundContex)
book.name = name
}
do {
try self.backgroundContex.save()
completion(nil)
} catch {
completion(error)
}
}
}
func saveBooks(names: [String]) -> AnyPublisher<Void, Error> {
backgroundContex.publisher {
for name in names {
let book = Book(context: self.backgroundContex)
book.name = name
}
try self.backgroundContex.save()
}
}
}
// MARK: - Fetch books
extension BookStorage {
func fetchBooks(completion: @escaping (Result<[Book], Error>) -> Void) {
backgroundContex.perform {
do {
let books = try self.backgroundContex.fetch(Book.all)
completion(.success(books))
} catch {
completion(.failure(error))
}
}
}
func fetchBooks() -> AnyPublisher<[Book], Error> {
backgroundContex.fetchPublisher(Book.all)
}
}