Dynamic Object in Fetch Request
cliftonlabrum opened this issue · 2 comments
This project was super helpful. I didn't understand much of what I read about Combine with Core Data until I looked through your code. Thank you!
I have a question for you. Let's pretend you have another Entity in Core Data called Project. A user can select various projects and view Items within each (one Project, many Items). When they switch the project in the UI, it should update which project is referenced in an NSPredicate here:
extension Item {
// MARK: - NSFetchRequests for Items
@nonobjc public class func fetchItemsAll() -> NSFetchRequest<Item> {
let name = "\(Self.self)"
print("Running fetch request \(name) for all")
let request = NSFetchRequest<Item>(entityName: name)
request.sortDescriptors = []
request.predicate = NSPredicate(format: "project = %@", project) //<-- predicate here
return request
}
}
It seems that once the publishers are set up, they are only set to use whatever is initially defined for project. But if the user changes it, I need the publisher to execute again, perform a new fetch request, and deliver the updated data to my views.
Any idea how I might pull that off? I assume that project would live in its own ObservableObject like this:
class AppState: ObservableObject{
static let shared = AppState()
@Published var project: Project!
}
...but I don't understand how to make the publishers fire again based on the project change.
Any ideas?
Hi Clifton,
Will take me a days or so context switch fully back to the joys of CoreData/Publishers/Combine etc but need something similar myself so wiil have a look/ponder this week.
fwiw I'm hoping it'll be fairly simple, but know that usually means I'm missing something - so if you've cracked it in the meantime do let me know as I'd be interested in what you've come up with :-)
Kind regards
Jon
Thanks for your reply. I did find a solution, yes. You can see the answers given here: https://stackoverflow.com/questions/66253532/reinitialize-combine-publishers-when-user-changes-global-object/66253686
As long as you have an @ObservableObject that manages your project change (or a workspace as shown in the SO question), then you can simply listen for it and setup your Combine publishers again and have them pass in the new value that your NSPredicate uses. 🙂