SwiftUI CoreData Async fetch

Viewed 217

I am using CoreData in my macOS Application with SwiftUI. I mainly make use of the @FetchRequest in SwiftUI, to make my request to the database.

I have noticed that the FetchRequest takes more time when I have several objects in database. Furthermore I am building a List with Images from that data. When I want to show that View with that FetchRequest inside, the View takes several seconds to be loaded.

I think this is due to the fact that the FetchRequest is performed on the Main Thread. I am looking for a way to make a Fetch Request to CoreData but in a asynchronous way, so the UI is being displayed directly.

However, I still want to make use of FetchRequest and automatically UI updates, when there are new records in the database.

I though of using ObservableObjects and Publishing my Results as via @Published, which would work asynchronous, however I would have to pull manually for updates.

That's the way I do requests via @FetchRequest

struct ViewA: View {

    @FetchRequest(entity: Venue.entity(), sortDescriptors:[NSSortDescriptor(key:"name", ascending: true, selector: #selector(NSString.localizedStandardCompare(_:)))]) var venueItems: FetchedResults<Venue>

And when I display ViewA, somewhere on a condition like that, it takes some seconds to load the View.

struct ViewWrapper: View {
    @State var currentView = 0

    var body: some View 
    {
        if(currentView == 0) { 
            Text("Dummy View")
        } else {
            ViewA() //<< when this view gets active, it takes some time to load. I need async inside View A
        }
    }

TL.DR:

I want to use @FetchRequest wrapper, however in a asynchronous way so the UI is being displayed right away and the fetch is being done in the background. How is it possible with SwiftUI?

0 Answers
Related