目录
中规中矩的 Retrofit+OkHttp+ViewModel 使用介绍。
为什么选择 LiveData、Retrofit 和 OkHttp?
在 Activity 中使用 ViewModel 和 LiveData
中规中矩的 Retrofit+OkHttp+ViewModel 使用介绍。
在现代 Android 开发中,使用 LiveData、Retrofit 和 OkHttp 进行网络请求和数据处理已经成为一种标准做法。这篇博文将详细介绍如何将这三者结合起来,构建一个高效、可维护的网络请求框架。
为什么选择 LiveData、Retrofit 和 OkHttp?
-
LiveData:LiveData 是一种可观察的数据持有者类,具有生命周期感知能力。它能与 Android 的生命周期组件无缝集成,确保 UI 组件只在活跃状态下更新,从而避免内存泄漏和崩溃问题。
-
Retrofit:Retrofit 是一个强大的类型安全的 HTTP 客户端,用于 Android 和 Java。它简化了网络请求的创建和处理过程,支持多种数据转换器(如 Gson、SimpleXML),并与 OkHttp 无缝集成。
-
OkHttp:OkHttp 是一个高效的 HTTP 客户端,支持连接池、缓存、重定向和失败重试等功能。它为 Retrofit 提供了底层支持,并且可以通过拦截器进行灵活的请求和响应处理。
项目依赖
首先,在你的 build.gradle
文件中添加以下依赖项:
dependencies {
implementation 'com.squareup.retrofit2:retrofit:2.9.0'
implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
implementation 'com.squareup.okhttp3:logging-interceptor:4.9.3'
implementation 'androidx.lifecycle:lifecycle-livedata-ktx:2.3.1'
implementation 'androidx.lifecycle:lifecycle-viewmodel-ktx:2.3.1'
}
配置 OkHttpClient 和 Retrofit
创建一个 ApiClient
类来配置 OkHttpClient 和 Retrofit 实例:
public class ApiClient {
private static final String BASE_URL = "https://api.example.com/";
private static Retrofit retrofit = null;
public static Retrofit getClient() {
if (retrofit == null) {
HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
logging.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(logging)
.build();
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.client(client)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit;
}
}
创建数据模型和 API 接口
定义一个数据模型类和一个 API 接口来描述网络请求:
public class User {
@SerializedName("id")
private int id;
@SerializedName("name")
private String name;
@SerializedName("email")
private String email;
// Getters and Setters
}
public interface ApiService {
@GET("users")
Call<List<User>> getUsers();
}
创建 Repository 类
创建一个 UserRepository
类来管理数据操作:
public class UserRepository {
private ApiService apiService;
public UserRepository() {
apiService = ApiClient.getClient().create(ApiService.class);
}
public LiveData<List<User>> getUsers() {
final MutableLiveData<List<User>> data = new MutableLiveData<>();
apiService.getUsers().enqueue(new Callback<List<User>>() {
@Override
public void onResponse(Call<List<User>> call, Response<List<User>> response) {
if (response.isSuccessful()) {
data.setValue(response.body());
}
}
@Override
public void onFailure(Call<List<User>> call, Throwable t) {
data.setValue(null);
}
});
return data;
}
}
创建 ViewModel 类
public class UserViewModel extends ViewModel {
private UserRepository userRepository;
private LiveData<List<User>> users;
public UserViewModel() {
userRepository = new UserRepository();
users = userRepository.getUsers();
}
public LiveData<List<User>> getUsers() {
return users;
}
}
在 Activity 中使用 ViewModel 和 LiveData
在 Activity 中使用 ViewModel 和 LiveData 来观察数据变化:
public class MainActivity extends AppCompatActivity {
private UserViewModel userViewModel;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
userViewModel = new ViewModelProvider(this).get(UserViewModel.class);
userViewMod