Bhaskar Mart
Bhaskar Mart

Reputation: 47

How to get Call Back from ViewModel to View in Android

I have ViewModel

  class MyViewModel extends BaseViewModel{
     public void foo(){
      // some code or return some boolean
      }
    }

View Class

    class MyView extends View{
    private MyViewModel myviewmodel;
        public void bindTo(MyViewModel viewModel) {
    this.viewModel = viewModel;
    context = viewModel.getContext();
    validateView();
    requestLayout();
}
private validateView(){

//some code
}


    }

this bind view method bind with adapter I want to get call back in Myview class when ever i will validateView will call please suggest me how get call back from Viewmodel method to View in android.

Upvotes: 0

Views: 1764

Answers (2)

Ehsan souri
Ehsan souri

Reputation: 329

it is best practice to use live data for communicating from viewmodel to your view.

class MyViewModel {
    private MutableLiveData<Boolean> state = new MutableLiveData<Boolean>;

    public LiveData<Boolean> getState() {
        return state;
    }
    

    public void foo() {
        //bool = value returned of your work 
        state.setValue(bool);
    } }


class Myview extends View {

    public void onCreate() {
         viewmodel.getState().observe(this, observer); // 'this' is life cycle owner

    }

    final Observer<Boolean> observer = new Observer<Boolean>() {
           @Override
           public void onChanged(@Nullable final Boolean state) {
               // do your work with returned value
           }
    }; }

for more details refer to this

Upvotes: 1

Dreamers
Dreamers

Reputation: 11

Correct Me if i wrong

  • first you need to make interface class
public interface ViewModelCallback {
    void returnCallBack(Boolean mBoolean);
}
  • then your View class implements that interface class & Override that method
class MyView extends View implements ViewModelCallback

 @Override
    public void returnCallBack(Boolean mBoolean) {
        //here you will retrieve callback
       // Do Something
    }
  • Next you just pass a value from your view model
class MyViewModel {
    private ViewModelCallback myViewCallBack;

    public void foo() {
        Boolean yourReturnValue = false;
        myViewCallBack.returnCallBack(yourReturnValue);
    }
}

Upvotes: 0

Related Questions