'.onReceive do not work when @Published property is changed [duplicate]
I have a @Published property in ViewModel and .onReceive in View. When my @Published var changes the .onReceive is not even executed.
View is the list of vaccinations. If user clicks "plus button" the new view is pushed. When user clicks on "add new vaccination" the uploadVaccination
function is called. It is changing the @Published var didUploadVaccination
to true
and dismissing the "add new vaccination" view. The previous view has .onReceive(uploadViewModel.$didUploadVaccination)
at the end so i think it should work, when just dismissed view changed it to "true". But it do not work.
Any suggestions? Thanks!
class UploadVaccinationViewModel: ObservableObject {
@Published var didUploadVaccination = false
let service = VaccinationService()
func uploadVaccination(medicineName: String,
lot: String,
expirationDate: String,
applicationDate: String,
comment: String) {
service.uploadVaccination(medicineName: medicineName,
lot: lot,
expirationDate: expirationDate,
applicationDate: applicationDate,
comment: comment) { success in
if success {
self.didUploadVaccination = true
} else {
// show errors here...
}
}
}
}
struct VaccinationsListView: View {
@ObservedObject var viewModel = VaccinationsViewModel()
@StateObject var uploadViewModel = UploadVaccinationViewModel()
var body: some View {
ZStack {
// ...
}
.onReceive(uploadViewModel.$didUploadVaccination) { success in
if success {
viewModel.fetchUserVaccinations()
print("success")
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|