Reputation: 47
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
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
Reputation: 11
Correct Me if i wrong
public interface ViewModelCallback {
void returnCallBack(Boolean mBoolean);
}
class MyView extends View implements ViewModelCallback
@Override
public void returnCallBack(Boolean mBoolean) {
//here you will retrieve callback
// Do Something
}
class MyViewModel {
private ViewModelCallback myViewCallBack;
public void foo() {
Boolean yourReturnValue = false;
myViewCallBack.returnCallBack(yourReturnValue);
}
}
Upvotes: 0