The bad news: the code is not really in the spirit of MVVM. The view model references Button.OnClickListener - a view specific class that really shouldn’t in the view model.
The implementation of the onClick method has a View parameter… how would you write a unit test that passed in a View to the view parameter?
Step 3 - create a Command class to execute button clicks
An easy way to clean this up is to create a Command class.
This could secretly expose the OnClickListener interface (among others potentially). However, the view model does not need to know about all this View-i-ness.
That’s better. The view model doesn’t know how the caller will execute the command. The view model exposes the command and the details of how Command.onExecute() gets called is hidden away.
Binding directly to a method
New to the Data Binding Library in RC1 (instead of RC0), the Android Data Binding Guide states that you can bind an onClick handler directly to a method on the view model, like so:
And the view model implementation:
However, when compiling I kept getting this error:
Execution failed for task ‘:app:compileDebugJavaWithJavac’.
java.lang.RuntimeException: failure, see logs for details.
cannot generate view binders java.lang.NullPointerException at
While the simplicity of this approach is very appealing, it still suffers from the problem that the method gets passed an instance of View, so I have mixed feelings about whether to use this approach or not (if it compiled for me, which it currently does not).