Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ViewModel without reference to View with Camera 2

In MVVM, a ViewModel must never reference a view. But how achieve it for use of Camera 2 API? For Camera setup, there are TextureView parameters needed (for example TextureView.surfaceTexture, TextureView.isAvailable, TextureView.width).

I'm trying to put logic from Camera2Basic example to a ViewModel. Is it clean solution to pass needed values by custom cameraInit(...) function or is it better to keep that code in the fragment?

like image 358
Francis Avatar asked Mar 20 '26 05:03

Francis


1 Answers

In general as part of MVVM the ViewModel is the component between your view (Fragment) and the model (some file manager in your case to save the image to a file). As you already mentioned, best practice for ViewModel is not to know anything about views. Considering this the ViewModel should accept some data from the view (the bitmap for example) and pass it to the model. You can achieve this by handling all the view dependent code in your Fragment (or some helper class handling the camera if you want to keep your Fragment as clean as possible) and pass it to the ViewModel.

The main aim of doing it this way is the possibility to test your ViewModels with simple Unit tests without the need of instrumentation. It is always important to know that using architectures like MVVM or MVP will NOT reduce the complexity of you code, in general the complexity will be even increased since you have the same logic plus overhead of the architecture. Because of this fact you always have to consider if it is worth to apply MVVM (it wont help much if you don't want to test your code anyway and the classes are not to large anyway).

like image 171
Andre Avatar answered Mar 24 '26 17:03

Andre