Inspired by ReactiveCocoa and Core Data Concurrency
- You will no longer need to use method
perform(_:)
directly withdo catch
. - You can forget about the callback based api when working with CoreData.
- NSManagedObjectContext produce Publisher
- NSManagedObjectContext + Scheduler
Add dependency to Package.swift
...
.package(url: "https://github.com/Alexander-Ignition/CombineCoreData", from: "0.0.3"),
... and your target
.target(name: "ExampleApp", dependencies: ["CombineCoreData"]),
Wrap any operation with managed objects in context with method publisher(_:)
.
import CombineCoreData
managedObjectContext.publisher {
// do something
}
Full examples you can see in Sources/Books. This module contains Book and BookStorage that manages books.
Example of asynchronously saving books in а backgroundContex
on its private queue.
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()
}
}
Example of asynchronously fetching books in а backgroundContex
on its private queue.
func fetchBooks() -> AnyPublisher<[Book], Error> {
backgroundContex.fetchPublisher(Book.all)
}
You can use NSManagedObjectContext
instead of OperationQeue
, DispatchQueue
or RunLoop
with operators receive(on:)
and subscribe(on:)
let subscription = itemService.load()
.receive(on: viewContext)
.sink(receiveCompletion: { completion in
// Receive `completion` on main queue in `viewContext`
print(completion)
}, receiveValue: { (items: [Item]) in
// Receive `[Item]` on main queue in `viewContext`
print(book)
})
CombineCoreData
extends NSManagedObjectContext
to adapt the Scheduler
protocol. Because NSManagedObjectContext
has a private queue and and schedule task through method perform(_:)
.