@Jay Below is an abbreviated example that is similar to the structure of my app and should provide reproducibility.
You will notice 3 key indicators that the view is invalidating rapidly.
- The UI becomes extremely laggy
- OnChange of the realm var from @ObservedResults prints to console extremely quickly
- An error on the view
onChange(of: Results<Dogs>) action tried to update multiple times per frame.
EDIT: I should note that I do not see the same invalidation issue if I replace the dogs variable in the onChange function with either the realm environmental variable passed to the view or the realm variable within the RealmModel if I pass the ObservableObject RealmModel to the HomeScreen view.
RealmModel.swift
import Foundation
import RealmSwift
public class RealmModel: ObservableObject {
@Published var realm: Realm?
@Published var loggedIn: Bool?
}
init() {
app = RealmSwift.App(id: "_______")
realmConfig = app?.currentUser?.flexibleSyncConfiguration()
realmConfig?.objectTypes = [Dogs.self]
realm = try! await Realm(configuration: realmConfig!, downloadBeforeOpen: .never)
// Code to add subscriptions for Dogs
}
ContentView.swift
import SwiftUI
import RealmSwift
struct ContentView : View {
@StateObject var realmModel = RealmModel()
var body: some View {
if realmModel.realm != nil{
HomeScreenView()
.environment(\.realm, auth.realm!)
}
}
}
}
HomeScreenView.swift
import SwiftUI
import RealmSwift
struct HomeScreenView: View {
@ObservedResults(Dogs.self) var dogs
var body: some View {
ScrollView {
ForEach(dogs) { dog in
Text("Dog object")
}
}
.onChange(of: dogs) { newValue in
print("View refreshing")
}
}
}
Thank you for taking a look