我想用MVVM模式实现一个android应用程序。我的应用程序有几个活动和片段。每个活动或片段都有一个自定义操作(向服务器发送请求,向数据库查询,从文件读取等)。我的应用程序具有用于与数据库,网络,文件等进行交互的多个模块。问题是某些操作需要与多个组件联系,然后将其结果汇总并更新在视图中观察到的LiveData。 是否可以编写一个可以在我所有viewModel中使用的通用包装器?(我知道Transformations(switch或switchMap)和MediatorLiveData,但需要在Activity / Fragment中观察它们)
>public class RegisterPhoneActivity extends
AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ActivityRegisterPhoneBinding binding = DataBindingUtil.setContentView(this, R.layout.activity_register_phone);
viewModel = ViewModelProviders.of(this).get(RegisterMobileViewModel.class);
binding.setViewModel(viewModel);
binding.setLifecycleOwner(this);
viewModel.getResponse().observe(this, new Observer<BaseResponse>() {
@Override
public void onChanged(BaseResponse baseResponse) {
//do something
}
});
}
}
public class RegisterMobileViewModel extends ViewModel {
public void onRegisterButtonClick() {
BaseSender.getInstance().sendRequest(new RegisterCommand());
}
public LiveData getResponse(){
BaseSender.getInstance.getResponse();
}
}
public class BaseSender {
//observed in Activity -- this design only works when i have a single network call
private MutableLiveData<String> response = new MutableLiveData<>();
private static BaseSender instance;
private BaseSender() {
}
public static BaseSender getInstance() {
if (instance == null) {
instance = new BaseSender();
}
return instance;
}
private class SenderHolder extends AsyncTask<String, Void, String> {
SenderHolder() {
}
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected String doInBackground(String... strings) {
// sending request to server
}
@Override
protected void onPostExecute(String s) {
response.setValue(s);
}
}
public MutableLiveData getResponse() {
return responseObject;
}
}