Kyle
10/02/2023, 3:30 PMval mileageLog: StateFlow<List<MileageLogEntry>?> = _mileageLog.asStateFlow()
and in swiftUI I’m trying to display all of the items,
List {
ForEach(viewModel.mileageLog!, id: \.self) { entry in
MileageLogListItem(viewModel: viewModel, entry: entry, showEntryEditor: $showEntryEditor)
}
}
but when I emit a new list I get [SwiftUI] Publishing changes from background threads is not allowed; make sure to publish values from the main thread (via operators like receive(on:)) on model updates.
. What’s the appropriate way to get the List to refresh in swift code?Rick Clephas
10/02/2023, 3:42 PMmileageLog
look like? Also what logic are you using to propagate the state changes to Swift?Kyle
10/02/2023, 3:45 PM_mileageLog.emit(/* new list */)
and I’m using rickclephas’ KMM-ViewModel library with a viewmodel in kotlin and it being referenced in swift with
@StateViewModel *var* mileageLogViewModel: MileageLogViewModel = InjectApplicationComponent().mileageLogViewModel
Kyle
10/02/2023, 3:50 PMRick Clephas
10/02/2023, 3:55 PMemit
call not to be on the main thread. But that doesn't seem to be the case.
Are you sure the error message is about the mileageLog
?Kyle
10/02/2023, 4:15 PMRick Clephas
10/02/2023, 4:19 PMKyle
10/02/2023, 4:24 PMviewModelScope.coroutineScope.launch
The list still isn’t updating though so still have to figure that outKyle
10/02/2023, 4:30 PMRick Clephas
10/02/2023, 4:41 PMwithContext(Dispatchers.Main) {}
call. Which will make sure to run the emit on the main thread, while still waiting for the emit call to complete before returning from deleteMileageLogEntry
.
On the Swift side just make sure to use one of the @XViewModel
property wrappers (e.g. @ObservedViewModel
) on the viewModel
property. That should be enough to propagate the changes to SwiftUI.Kyle
10/02/2023, 5:00 PMrobercoding
08/20/2024, 4:37 PM@ObservedViewModel
that I forgot to apply
class HomeModel: ObservableObject {
// Fix log spam: Publishing changes from background threads is not allowed; make sure to publish values from the main thread.
// Ensure the changes are done in the Main thread
@ObservedViewModel
private var viewModel = HomeComponent().homeViewModel
...
}
Solved thanks to this thread 😂🫶