Hi,
I’ve been encountering use cases where I can’t help but want to make my ViewModels communicate with each other. Imagine an app with several ViewModels as EnvironmentObjects, where each handles rather extensive business logics about different things.
As an example and for the sake of discussion, imagine there’s first a WeatherViewModel that handles business logic about weather data, and second a StoreViewModel that handles business logic notably about the frequency of visits to a store.
Say there was a view in which we would like to plot the probability of rain against frequency of visits, compute correlations and whatnot… (Again… for the sake of discussion)
We would need to make calculations with data that comes from 2 separate viewmodels.
What are some best practices for this type of problem?
For now I was thinking of creating a third viewmodel that has access to the other two. It could communicate with them either via a sort of dependency injection:
class ThirdViewModel: ObservableObject {
let fvm: FirstViewModel
let svm: SecondViewModel
init(fvm: FirstViewModel, svm: SecondViewModel) {
self.fvm = fvm
self.svm = svm
}
@Published var somePropertiesToDisplayInTheView:[Stuff] = []
func doComputationsWithFvmAndSvmData() async {
}
}
Or I was thinking of simply injecting the view models not necessarily in the whole thirdviewmodel, but only in a specific method like this:
func doComputationsWithFvmAndSvmData(fvm:FirstViewModel,svm:SecondViewModel) async {
}
And then have the view call this function.
I don’t want to centralize everything at the view level either, I try to avoid having too much logic there. At the same time, the solutions I mentioned feel a bit weird and I also don’t want to run into data races issues.
Has anyone encountered questions like this and how did you choose to solve it?
Many thanks!
Raph