Ammar Ahmad
Ammar Ahmad

Reputation: 874

SwiftUI Using on Receive with @FetchRequest Publisher

I try to observe the changes in @FetchRequest publisher by using onReceive as shown in the code bellow, It's work but I have on issue I want to fix it, the publisher publish to many values and I just want to receive one value to know the change in @FetchRequest is happened.

Example Code

struct TodayView: View {
 
    @FetchRequest(fetchRequest: TodoTaskManager.allOverdueTasksFetchRequest)
    private var overdueTasks: FetchedResults<TodoTask>

    // Some views...

    .onReceive(overdueTasks.publisher.count()) { _ in
        print("tasks count: \(overdueTasks.count)") // The print times equals tasks count x 2
       }
}

Upvotes: 4

Views: 739

Answers (1)

zouritre
zouritre

Reputation: 655

Use collect() on the @FetchRequest publisher you observe with onReceive

.onReceive(myObjects.publisher.collect(), perform: { objects in
        print(objects.count)
})

Upvotes: 1

Related Questions