当 ViewModel
与 Retrofit
结合进行网络请求时,可以实现高效、可维护的网络数据获取和处理。
首先,确保已经添加了 Retrofit
的相关依赖。
创建一个 Retrofit
服务接口来定义网络请求的方法:
interface YourApiService {
@GET("yourEndpoint")
Call<YourResponseData> getData();
}
在 ViewModel
中进行网络请求的操作:
public class YourViewModel extends ViewModel {
private YourApiService apiService;
public YourViewModel() {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("yourBaseUrl")
.build();
apiService = retrofit.create(YourApiService.class);
}
public LiveData<YourResponseData> getData() {
MutableLiveData<YourResponseData> data = new MutableLiveData<>();
apiService.getData().enqueue(new Callback<YourResponseData>() {
@Override
public void onResponse(Call<YourResponseData> call, Response<YourResponseData> response) {
if (response.isSuccessful()) {
data.setValue(response.body());
}
}
@Override
public void onFailure(Call<YourResponseData> call, Throwable t) {
// 处理请求失败的情况
}
});
return data;
}
}
在视图(如 Activity
或 Fragment
)中观察 LiveData
的变化并进行相应的处理:
public class YourActivity extends AppCompatActivity {
private YourViewModel viewModel;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
viewModel = new ViewModelProvider(this).get(YourViewModel.class);
viewModel.getData().observe(this, new Observer<YourResponseData>() {
@Override
public void onChanged(YourResponseData responseData) {
// 根据获取到的数据更新视图
}
});
}
}
通过这种方式,ViewModel
负责管理网络请求的逻辑,Retrofit
负责实际的网络通信,LiveData
则用于将获取到的数据传递给视图进行展示和处理,实现了职责的清晰分离,提高了应用的可维护性和稳定性。