mvvm+rxjava2+retrofit+room实现缓存请求到的数据详细代码并且先从缓存拿数据再从服务端获取覆盖代码实现
时间: 2023-09-10 18:11:44 浏览: 98
好的,下面是一个简单的示例代码:
1. 定义数据模型
```java
@Entity
public class User {
@PrimaryKey
public int id;
public String name;
public int age;
}
```
2. 定义网络请求接口
```java
public interface ApiService {
@GET("users/{id}")
Single<User> getUser(@Path("id") int id);
}
```
3. 定义本地数据库操作接口
```java
@Dao
public interface UserDao {
@Query("SELECT * FROM User WHERE id = :id")
Maybe<User> getUserById(int id);
@Insert(onConflict = OnConflictStrategy.REPLACE)
Completable insertUser(User user);
}
```
4. 定义数据仓库
```java
public class UserRepository {
private ApiService apiService;
private UserDao userDao;
public UserRepository(ApiService apiService, UserDao userDao) {
this.apiService = apiService;
this.userDao = userDao;
}
public Single<User> getUser(int id) {
Maybe<User> local = userDao.getUserById(id);
Single<User> remote = apiService.getUser(id)
.doOnSuccess(userDao::insertUser);
return Maybe.concat(local, remote.toMaybe())
.firstElement()
.toSingle();
}
}
```
5. 在ViewModel中使用数据仓库
```java
public class UserViewModel extends ViewModel {
private CompositeDisposable disposables = new CompositeDisposable();
private UserRepository userRepository;
private MutableLiveData<User> user = new MutableLiveData<>();
private MutableLiveData<Throwable> error = new MutableLiveData<>();
public UserViewModel() {
ApiService apiService = createApiService();
UserDao userDao = createRoomDatabase().userDao();
userRepository = new UserRepository(apiService, userDao);
}
public LiveData<User> getUser() {
return user;
}
public LiveData<Throwable> getError() {
return error;
}
public void loadUser(int id) {
disposables.add(userRepository.getUser(id)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(this::onUserLoaded, this::onError));
}
private void onUserLoaded(User user) {
this.user.setValue(user);
}
private void onError(Throwable throwable) {
this.error.setValue(throwable);
}
@Override
protected void onCleared() {
disposables.clear();
}
}
```
在上面的代码中,我们通过使用`Maybe`来先从本地数据库获取用户信息,如果本地数据库中没有该用户信息,则再从网络请求获取用户信息,并将其存入本地数据库。最后将获取到的用户信息通过`LiveData`传递给View层显示。同时,我们还可以通过`Throwable`类型的错误信息来告诉View层加载过程中出现的错误。
阅读全文