How do you let SwiftUI View know that ViewModel's computed property has changed?

Imagine you have ViewModel which computed property may change from time to time:

import Foundation

class ViewModel: ObservableObject {
	private var val = 42;
	
	var compProp: Int {
		return val
	}

	func maybeChange() {
		if (Int.random(in: 0..<2) == 1) {
			val += 1
			???
			//heyViewThePropertyIsChanged(nameof(compProp))
		}
	}
}

How could you force the View:

import SwiftUI

struct ContentView: View {
	@StateObject var viewModel: ViewModel
	var body: some View {
		VStack {
			Text("\(viewModel.compProp)").font(.title)
		}
		.frame(minWidth: 320)
		.toolbar {
			Button(action: viewModel.maybeChange) {
				Label("Maybe", systemImage: "gear.badge.questionmark")
			}
		}.padding()
	}
}

to reflect such a change?

For ObservableObject you can use

objectWillChange.send()

Did you try to use publish ?

See details here: https://stackoverflow.com/questions/62740812/swiftui-observableobject-with-a-computed-property

Or here to use @Observable: https://medium.com/@jywvgkchm/understanding-observation-in-swift-simplifying-swiftui-development-73853a06e86a

I was curious if you've considered migrating to Observable macro ?

And to add to @Claude31's point, With a computed property, when a property that is used changes, the UI updates as well. Discover Observation in SwiftUI WWDC Session covers the cover and it walks you through a sample code as well.

How do you let SwiftUI View know that ViewModel's computed property has changed?
 
 
Q