observable core data model in swift

To make a Core Data model observable in Swift using RxSwift, we can use the RxCoreData library. Here are the steps:

  1. Add pod 'RxCoreData' to your Podfile and run pod install in Terminal

  2. Import RxCoreData and RxSwift

main.swift
import RxCoreData
import RxSwift
33 chars
3 lines
  1. Fetch the desired Core Data entity that we want to observe, and convert it to a Observable<[NSManagedObject]> using asObservable() method
main.swift
let request: NSFetchRequest<Entity> = Entity.fetchRequest()
let entitiesObservable = context.rx
    .entities(fetchRequest: request)
    .asObservable()
153 chars
5 lines
  1. Subscribe to the entitiesObservable to receive updates whenever the Core Data entity gets added/updated/deleted
main.swift
entitiesObservable.subscribe(onNext: { entities in
        // Handle updated entities
    }).disposed(by: disposeBag)
118 chars
4 lines

We can also filter/sort the entities based on our requirements by modifying the fetch request before converting it to an Observable.

gistlibby LogSnag