在Android MVVM中,当相同的数据来自不同服务器端点的响应的一部分时,可以通过以下步骤从另一个存储库中更新存储库的数据:
public class MyViewModel extends ViewModel {
private MutableLiveData data = new MutableLiveData<>();
private MyRepository repository;
public MyViewModel() {
repository = new MyRepository();
}
public LiveData getData() {
return data;
}
public void fetchDataFromServer1() {
repository.getDataFromServer1(new MyCallback() {
@Override
public void onResponse(String response) {
data.setValue(response);
}
@Override
public void onFailure(String error) {
// Handle error
}
});
}
public void fetchDataFromServer2() {
repository.getDataFromServer2(new MyCallback() {
@Override
public void onResponse(String response) {
data.setValue(response);
}
@Override
public void onFailure(String error) {
// Handle error
}
});
}
}
public class MyRepository {
private ApiService apiService;
public MyRepository() {
apiService = RetrofitClient.getApiService();
}
public void getDataFromServer1(MyCallback callback) {
apiService.getDataFromServer1().enqueue(new Callback() {
@Override
public void onResponse(Call call, Response response) {
if (response.isSuccessful()) {
callback.onResponse(response.body());
} else {
callback.onFailure("Error");
}
}
@Override
public void onFailure(Call call, Throwable t) {
callback.onFailure(t.getMessage());
}
});
}
public void getDataFromServer2(MyCallback callback) {
apiService.getDataFromServer2().enqueue(new Callback() {
@Override
public void onResponse(Call call, Response response) {
if (response.isSuccessful()) {
callback.onResponse(response.body());
} else {
callback.onFailure("Error");
}
}
@Override
public void onFailure(Call call, Throwable t) {
callback.onFailure(t.getMessage());
}
});
}
}
MyCallback
,用于处理服务器响应的回调。public interface MyCallback {
void onResponse(String response);
void onFailure(String error);
}
public class MyActivity extends AppCompatActivity {
private MyViewModel viewModel;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
viewModel = new ViewModelProvider(this).get(MyViewModel.class);
viewModel.getData().observe(this, new Observer() {
@Override
public void onChanged(String data) {
// Update UI with new data
}
});
// Fetch data from server1
viewModel.fetchDataFromServer1();
// Fetch data from server2
viewModel.fetchDataFromServer2();
}
}
在上述代码中,ViewModel负责从Repository获取数据并将其更新到LiveData中。Activity或Fragment观察LiveData的变化,并在数据更新时更新UI。Repository类使用Retrofit或其他网络库来从服务器获取数据,并使用回调通知ViewModel数据的变化。
请确保在代码中替换相应的网络请求代码,并根据实际情况进行修改。