I have attached an onReceive modifier to a view in SwiftUI. The purpose of the subscription is to respond to changes in an @Published property greeting, part of a view Model object.
The view contains a Segmented Picker. The segmented picker uses another property in the view model -- index.
Inexplicably, when user changes the segmented picker selection the onReceive block is called, even though the Publisher greeting has not changed.
import SwiftUI
import Combine
class Model: ObservableObject {
@Published var selectedIndex = 0
@Published var greeting = "initial"
}
struct ContentView: View {
@ObservedObject var model: Model
let pickerTitles = ["One", "Two", "Three"]
var body: some View {
VStack {
return Picker("Options", selection: $model.selectedIndex) {
ForEach(0 ..< pickerTitles.count) { index in
Text(self.pickerTitles[index])
}
}.pickerStyle(SegmentedPickerStyle())
}
.onReceive([model.greeting].publisher){str in
print(str)
}
}
}
What's going on? Above code is the entirety of the codebase.
RE: SUMMARY
I specify a Publisher in .onReceive block. That specified property -- greeting -- never changes. When another property -- index -- is changed by the Picker in the same ObservedObject, the .onReceive block is mysteriously called.
