Context
Suppose I have two objects, like this:
final class Parent: Object
{
@Persisted var children: List<Child>
@Persisted var hasFlaggedChildren: Bool
}
final class Child: Object
{
@Persisted var flags: MutableSet<String>
}
Question
Is it valid/safe to use a query inside a write transaction where I’m updating the property being queried, like this:
func update(children: [Child], newFlags: [String], removedFlags: [String])
{
try someRealm.write {
// Loop over `children` and, for each, insert all `newFlags`
// and remove all `removedFlags`.
// To update the `hasFlaggedChildren` property on `Parent`,
// can I do this in the same write transaction?
let parents: Results<Parent> = someRealm.objects(ofType: Parent.self)
for parent: Parent in parents
{
let flaggedKids: Results<Child> = parent.children.where({ $0.flags.count > 0 })
parent.hasFlaggedChildren = (flaggedKids.isEmpty) ? false : true
}
}
}
I’m worried that because the write transaction has not been committed when I query for Child
objects with an empty flags
set, the query will return “stale” results. Is that the case?
I have behavior in my app where the “hasFlaggedChildren” property is “out of sync” (it’s true
even though all children have empty flags
sets) and I believe the explanation might be this query-inside-the-write-transaction.
Thanks!