r/JavaFX • • Dec 04 '24
Discussion Dialogs in MVVM
There was recently a post how to display dialogs in MVCI. But what about dialogs in MVVM? It's actually not a simple question. For example, I decided to use dialog service, that knows and uses view:
in View:
viewModel.setDialogService(new DialogServiceImpl(this));In ViewModel:
var result = this.dialogService.openSomeDialog(someDialogVM);For example, we have a dialog that consists of AlertView and AlertViewModel. Now FooViewModel wants to show this dialog. FooViewModel knows only AlertViewModel but it doesn't know AlertView. So, we create a DialogService that is available in FooViewModel, something like
public interface FooDialogService extends DialogService {
void openAlertDialog(AlertViewModel dialogVM);
}and after that in FooViewModel
this.dialogService.openAlertDialog(alertVM)So, FooDialogService knows FooView and AlertView and has instance of AlertViewModel.
And what solution do you use?
View all comments
Show parent comment
2
u/hamsterrage1 Dec 04 '24
I mostly follow what you're describing. You have presumably created a MVVM construct for your Alert, and you are connecting it to your client MVVM constructs through the ViewModels. And that makes sense to me because my approach is to connect application components via whatever supplies the "Control" functionality. In MVC/MVCI that is the Controller, and in MVVM it's the ViewModel.
The only thing complicated about this architecture is that Dialogs, even Alerts, are supposed to be data collection tools, which is why they have a return value. But you can't really treat them as Functions because you can't really "wait" for a return value in a GUI. But they are usually modal, which means that you can have some sense of a Function, but you shouldn't program like that (because how does your client construct "know" that the AlertService is going to have a modal Dialog???).
That means that inside your Dialog MVVM you can treat
showAndWait()like a Function call, because that's what it's designed to do. But in the client MVVM, you cannot assume that. So you cannot right some code like this:But you would need to do something like this:
or you could design your AlertService a little bit like
Task, which hasonSucceeded. So maybe something like this:At least, that's the way that I would do it, although for something like an
AlertI probably wouldn't bother with the MVVM structure to implement it. Unless theAlertwas somehow super complicated.