例如,我有一个包含名称的列表,我想查看这些名称是否已经存在于会议室数据库中,或者名称是否已更改。如果还没有,则保存否则替换。 问题是我的逻辑必须保留在存储库中,直到正确的名称保存在room db中,然后在我的活动中观察它或在recyleradapter中显示它。 到目前为止,我已经完成了使用AsyncTask添加对象列表的操作,但是使用AsyncTask检索了对象列表(名称)并在存储库中操作该数据到目前为止还不是很幸运。 也许使用onPostExecute,然后将结果发送回存储库?
房间:
$request->ip()
AsyncTask:
@Dao
public interface NewUsersDao {
@Insert
long[] addNewUsers(NewUsersModel... newUsers);
@Query("SELECT DISTINCT * FROM search_users")
LiveData<List<NewUsersModel>> readAllUsersFromSQL();
}
存储库:
public class InsertAsyncTask extends AsyncTask<NewUsers, Void, Void> {
private NewUsersDao mNewUsersDao;
public InsertAsyncTask(NewUsersDao newUsersDao) {
mNewUsersDao = newUsersDao;
}
@Override
protected Void doInBackground(NewUsers... newUsers) {
mNewUsersDao.addNewUsers(newUsersModels);
return null;
}
}
ViewModelclass:
public static NewUserRepository getInstance(Context context){
if(repository == null){
repository = new NewUserRepository(context);}
}
return repository;
public NewUserRepository(Context context) {
mNewUsersDatabase = NewUsersDatabase.getInstance(context);}
for(final NewUsers namesObject: mNameList){
addUserToSql(namesObject) }
public void addUserToSql(NewUsers names){
new InsertAsyncTask(mNewUsersDatabase.getNewUsersDao()).execute(names);}
public LiveData<List<NewUsers>> readAllUsersFromSQL(){
return mNewUsersDatabase.getNewUsersDao().readAllUsersFromSQL();}
活动:
@RequiresApi(api = Build.VERSION_CODES.N)
public class NewUsersViewModel extends AndroidViewModel {
private static final String TAG = "NewUsersViewModel";
private NewUserRepository mNewUserRepository;
public NewUsersViewModel(@NonNull Application application) {
super(application);
mNewUserRepository = NewUserRepository.getInstance(application);}
public LiveData<List<NewUsersModel>> readAllUsersFromSQL(){
return mNewUserRepository.readAllUsersFromSQL();}
}