Search code examples
mvvmandroid-architecture-components

AAC: How return result (handle click) from ViewModel to activity?


I want to use in my project Android Architecture Components (AAC). Nice.

Here my activity:

    import androidx.appcompat.app.AppCompatActivity;
    public class TradersActivity extends AppCompatActivity  {
        private TradersViewModel tradersViewModel;

         @Override
         protected void onCreate(@Nullable Bundle savedInstanceState) {
              super.onCreate(savedInstanceState);


              tradersViewModel = ViewModelProviders.of(this).get(TradersViewModel.class);

              tradersViewModel.getIsEnableSwipeProgress().observe(this, new Observer<Boolean>() {

                    @Override
                    public void onChanged(Boolean isEnable) {
                        // do some work with UI
                    }
                });

        }

        // button click        
        public void onClickViewJson(Trader trader) {
             tradersViewModel.doClickJsonView(trader);
        }

    }

Here my ViewModel

public class TradersViewModel extends ViewModel {
private MutableLiveData<Boolean> isEnableSwipeProgress = new MutableLiveData<>();

 public void doClickJsonView(Trader trader) {
      // DO_SOME_COMPLEX_BUSINESS_LOGIC
 }

 public MutableLiveData<Boolean> getIsEnableSwipeProgress() {
      return isEnableSwipeProgress;
 }

}

In the screen I has button. And when click this button I call activity's method - onClickViewJson(Trader trader) .

This method call tradersViewModel.doClickJsonView(trader);

In the viewModel this method do some complex business logic. After method finish it work I need to return result (json) to the my activity.

How I can do this?


Solution

  • Remember that in MVVM, ViewModels have not idea about your view. Your ViewModel should expose variables so your views can observe and react over them.

     private MutableLiveData<Boolean> isEnableSwipeProgress = new MutableLiveData<>();
    
     private MutableLiveData<JSONDto> jsonLiveData = new MutableLiveData<>();
    
     public void doClickJsonView(Trader trader) {
          // DO_SOME_COMPLEX_BUSINESS_LOGIC
          jsonLiveData.postValue(/* the json you obtain after your logic finish */ )
     }
    
     public MutableLiveData<Boolean> getIsEnableSwipeProgress() {
          return isEnableSwipeProgress;
     }
    
     public LiveData<JSONDto> getJsonDto() {
          return this.jsonLiveData;
     }
    
    
    

    And in your view, you react over your jsonDto changes:

    tradersViewModel.getJsonDto().observe(this, new Observer<JSONDto>() {
    
                        @Override
                        public void onChanged(JSONDto json) {
                             if (json != null) {
                               // Do what you need here.
                             }
                        }
                    });