StartActivityForResult to get images from gallery in MVVM architecture?

Viewed 893

I am using MVVM architecture for my PhotoEditorActivity, the activity plays the View role. When user clicks "Pick Image" button, I want to start gallery to pick an image and get back its uri to update an ImageView. I am confused in where to call startActivityForResult().

  • Call startActivityForResult() from View: By this way, the activity processes everything, ViewModel and Model become redundant.
  • Call startActivityForResult() from ViewModel and View observes Uri from the ViewModel: I can pass Context to ViewModel to start activity, but I can not receive uri because ViewModel does not have onActivityResult().
  • Call startActivityForResult() from Model: View pass a Context to ViewModel, ViewModel continue passing the Context to Model. Using this way, I face the same issue with the second way.

Could you please help me how to properly apply MVVM for this business. What should each component contain? Thank you for your attention.

1 Answers

All Android related things are best handled in the View. Specifically making your code loosely coupled depends on what you intended to do with the image / file that you have selected. If for example you are trying to upload it as a bitmap, then you should create the bitmap in the view and pass it to the view model. Also, onActivityResult is now depreciated. See the official documentation for it here. You may also want to look at this answer for an example implementation of it.

Related