Alexander-Ignition / CombineCoreData

Combine + CoreData

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

๐Ÿšœ CombineCoreData ๐Ÿ—„

SPM compatible GitHub license GitHub Workflow Test

Inspired by ReactiveCocoa and Core Data Concurrency

  • You will no longer need to use method perform(_:) directly with do catch.
  • You can forget about the callback based api when working with CoreData.

Features

  • NSManagedObjectContext produce Publisher
  • NSManagedObjectContext + Scheduler

Instalation

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"]),

Usage

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.

Save objects

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()
    }
}

Fetch objects

Example of asynchronously fetching books in ะฐ backgroundContex on its private queue.

func fetchBooks() -> AnyPublisher<[Book], Error> {
    backgroundContex.fetchPublisher(Book.all)
}

Scheduler

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(_:).

About

Combine + CoreData

License:MIT License


Languages

Language:Swift 100.0%