Updated to @Observable, now the total not updated on each keystroke

Hi

I am developing an app for counting money. One view is for entering the intended destinations specified by a donor. Each destination has a row with a TextField that has an OnChange to keep it all numeric. The model that holds the data is a class called AllocationItems, which I recently changed from having the protocol ObservableObject to having the macro @Observable.

It mostly works the same, except that before with each key stroke the total would be updated, but now with the macro it only gets updated when I exit the current TextField by clicking on another TextField

How do I get it to update the total with each keystroke?

The code that shows the total is this: Text(allocations.totalAllocated.fmtCurrency)

where allocations is an instance of AllocationItems

with this definition: var totalAllocated: NSDecimalNumber { items.reduce(.zero) { $0 + $1.amountValue } }

I hope someone knows why this has changed and can suggest a simple fix.

I think I have the solution. I copied and pasted this into ChatGPT, adding that I was using SwiftUI. By picking the most hopeful looking bits from what it said I got the thing updating the total on each keystroke again.

It guessed my data names! It said to make class AllocationItem have the macro, so it is now:

@Observable class AllocationItem: Identifiable

And in AllocationRow (struct AllocationRow: View) I had to put @Bindable on the var declaration for the model:

@Bindable private var allocation: AllocationItem

Then I had to update a lazy property in AllocationItem:

@ObservationIgnored lazy var row: AllocationRow = .init(allocation: self)

With those 3 changes it worked.

If you fixed it, you should mark your answer as accepted so others know that there's a fix for the issue without having to read through the replies.

Secondly, a lot of wordy paragraphs with code interspersed isn't easy to read if you have issues with your code, so it would be appreciated if you would add a chunk of code to explain the initial issue and then the fixed code. Maybe not for this post, but certainly for future ones. Thanks!

Updated to @Observable, now the total not updated on each keystroke
 
 
Q