I am currently working on an android application that uses MVVM, live data and databinding. I have a use-case where I need to show a Comment button in multiple screens in my android app.

The business logic is simple, when the user clicks on the button I need to check if the user is logged-in to the app or not. If yes, I take the user to a screen where he would be able to view all comments. If not, then I need to show a login screen; and after login I show the comment's screen. I'd like to know if there is an efficient way to handle this so that I dont need to duplicate my code across multiple screens and view models.

Solution 1

One way I thought of doing this is to have the login button in a fragment which I include in all screens required. The fragment would have a view-model and the live data observer. Whenever the user clicks on the button, I check in the view model if the user is logged in or not. If yes I set the live data to have value LOGGED_IN else I set NOT_LOGGED_IN. When I receive the callback in my fragment I re-direct him the appropriate screen.

Problem with Solution 1

One problem I can see with the above approach is if the UI of the comment button changes I would need to write additional code in the fragment to handle that.

Solution 2

Pass the view model for the comment button as constructor to the view model of the activity

Although this would work fine, I haven't seen anyone do this. Are there any problems with approach 2?


Which of the above two methods would be better? Are there any other solution that you guys could help me with?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.