我第一次使用Room。我正在看一下LiveData概念。我知道我们可以将数据库中的记录提取到LiveData并附加了hasObservers。
@Query("SELECT * FROM users")
<LiveData<List<TCUser>> getAll();
但是我在后台执行同步,我需要从服务器获取数据并将其与RoomDatabase表中的数据进行比较,该表名为&#34; users&#34;然后从用户表中插入,更新或删除。如何在采取任何行动之前遍历LiveData列表?因为如果我把它放入for循环就会出错。
或者我不应该在这种情况下使用LiveData吗?
我想我需要打电话
<LiveData<List<TCUser>> getAll().getValue()
但这是正确的做法吗?这里有一些代码可以说明我想要做的事情:
List<User>serverUsers: Is the data received from a response from an API
private void updateUsers(List<User> serverUsers) {
List<UserWithShifts> users = appDatabase.userDao().getAllUsers();
HashMap<String, User> ids = new HashMap();
HashMap<String, User> newIds = new HashMap();
if (users != null) {
for (UserWithShifts localUser : users) {
ids.put(localUser.user.getId(), localUser.user);
}
}
for (User serverUser : serverUsers) {
newIds.put(serverUser.getId(), serverUser);
if (!ids.containsKey(serverUser.getId())) {
saveShiftForUser(serverUser);
} else {
User existingUser = ids.get(serverUser.getId());
//If server data is newer than local
if (DateTimeUtils.isLaterThan(serverUser.getUpdatedAt(), existingUser.getUpdatedAt())) {
deleteEventsAndShifts(serverUser.getId());
saveShiftForUser(serverUser);
}
}
}
其中:
@Query("SELECT * FROM users")
List<UserWithShifts> getAllUsers();
updateUsers()中的第一行是在插入新数据之前从数据库获取数据的正确方法,还是应该是
<LiveData<List<User>> getAll().getValue()
谢谢,
答案 0 :(得分:2)
如果我正确理解您的架构,则updateUsers位于AsyncTask或类似内容中。
这是我提出的方法,其中包括调整你的Dao以获得最大效果。您编写了大量代码来做出可能要求数据库做出的决定。
这也不是严密或高效的代码,但我希望它能说明这些库的更有效使用。
后台线程(IntentService,AsyncTask等):
/*
* assuming this method is executing on a background thread
*/
private void updateUsers(/* from API call */List<User> serverUsers) {
for(User serverUser : serverUsers){
switch(appDatabase.userDao().userExistsSynchronous(serverUser.getId())){
case 0: //doesn't exist
saveShiftForUser(serverUser);
case 1: //does exist
UserWithShifts localUser = appDatabase.userDao().getOldUserSynchronous(serverUser.getId(), serverUser.getUpdatedAt());
if(localUser != null){ //there is a record that's too old
deleteEventsAndShifts(serverUser.getId());
saveShiftForUser(serverUser);
}
default: //something happened, log an error
}
}
}
如果在UI线程(Activity,Fragment,Service)上运行:
/*
* If you receive the IllegalStateException, try this code
*
* NOTE: This code is not well architected. I would recommend refactoring if you need to do this to make things more elegant.
*
* Also, RxJava is better suited to this use case than LiveData, but this may be easier for you to get started with
*/
private void updateUsers(/* from API call */List<User> serverUsers) {
for(User serverUser : serverUsers){
final LiveData<Integer> userExistsLiveData = appDatabase.userDao().userExists(serverUser.getId());
userExistsLiveData.observe(/*activity or fragment*/ context, exists -> {
userExistsLiveData.removeObservers(context); //call this so that this same code block isn't executed again. Remember, observers are fired when the result of the query changes.
switch(exists){
case 0: //doesn't exist
saveShiftForUser(serverUser);
case 1: //does exist
final LiveData<UserWithShifts> localUserLiveData = appDatabase.userDao().getOldUser(serverUser.getId(), serverUser.getUpdatedAt());
localUserLiveData.observe(/*activity or fragment*/ context, localUser -> { //this observer won't be called unless the local data is out of date
localUserLiveData.removeObservers(context); //call this so that this same code block isn't executed again. Remember, observers are fired when the result of the query changes.
deleteEventsAndShifts(serverUser.getId());
saveShiftForUser(serverUser);
});
default: //something happened, log an error
}
});
}
}
您希望根据您决定使用的方法修改Dao
@Dao
public interface UserDao{
/*
* LiveData should be chosen for most use cases as running on the main thread will result in the error described on the other method
*/
@Query("SELECT * FROM users")
LiveData<List<UserWithShifts>> getAllUsers();
/*
* If you attempt to call this method on the main thread, you will receive the following error:
*
* Caused by: java.lang.IllegalStateException: Cannot access database on the main thread since it may potentially lock the UI for a long periods of time.
* at android.arch.persistence.room.RoomDatabase.assertNotMainThread(AppDatabase.java:XXX)
* at android.arch.persistence.room.RoomDatabase.query(AppDatabase.java:XXX)
*
*/
@Query("SELECT * FROM users")
List<UserWithShifts> getAllUsersSynchronous();
@Query("SELECT EXISTS (SELECT * FROM users WHERE id = :id)")
LiveData<Integer> userExists(String id);
@Query("SELECT EXISTS (SELECT * FROM users WHERE id = :id)")
Integer userExistsSynchronous(String id);
@Query("SELECT * FROM users WHERE id = :id AND updatedAt < :updatedAt LIMIT 1")
LiveData<UserWithShifts> getOldUser(String id, Long updatedAt);
@Query("SELECT * FROM users WHERE id = :id AND updatedAt < :updatedAt LIMIT 1")
UserWithShifts getOldUserSynchronous(String id, Long updatedAt);
}
这会解决您的问题吗?
注意:我没有看到您的saveShiftForUser
或deleteEventsAndShifts
方法。插入,保存和更新由Room同步执行。如果您在主线程上运行任一方法(我猜测这是您的错误来自哪里),您应该创建一个从appDatabase返回的daoWrapper,如下所示:
public class UserDaoWrapper {
private final UserDao userDao;
public UserDaoWrapper(UserDao userDao) {
this.userDao = userDao;
}
public LiveData<Long[]> insertAsync(UserWithShifts... users){
final MutableLiveData<Long[]> keys = new MutableLiveData<>();
HandlerThread ht = new HandlerThread("");
ht.start();
Handler h = new Handler(ht.getLooper());
h.post(() -> keys.postValue(userDao.insert(users)));
return keys;
}
public void updateAsync(UserWithShifts...users){
HandlerThread ht = new HandlerThread("");
ht.start();
Handler h = new Handler(ht.getLooper());
h.post(() -> {
userDao.update(users);
});
}
public void deleteAsync(User... users){
HandlerThread ht = new HandlerThread("");
ht.start();
Handler h = new Handler(ht.getLooper());
h.post(() -> {
for(User e : users)
userDao.delete(e.getId());
});
}
}