Reputation: 1521
My team have developed a new Android app which makes extensive use of Room.
I am unsure whether we are using AsyncTask correctly.
We have had to wrap all calls to insert/update/delete in AsyncTasks which results in a huge number of AsyncTasks. All the calls into Room are from background services. There is no direct Room access from activities or fragments - they get everything via LiveData.
An example call to insert a row:
AsyncTask.execute(() -> myModelDAO.insertInstance(myModel));
With this in the DAO:
@Insert
void insertInstance(MyModel model);
Upvotes: 14
Views: 15981
Reputation: 4870
To complete @CommonsWare answer, you can use the Executor class to execute Room queries into a background thread.
Executor myExecutor = Executors.newSingleThreadExecutor();
myExecutor.execute(() -> {
myModelDAO.insertInstance(myModel)
});
Google showed an example on their Android Architecture Components guide.
Upvotes: 24
Reputation: 1
You can use a callback like Consumer<List<object>>callback
.
For example:
roomManger.getAllUsertById(user.getId(), this, new Consumer<List<User>>() {
@Override
public void accept(List<Product> listOfUser) {
users.addAll(listOfUser)}
Upvotes: 0
Reputation: 2640
AsyncTask.execute(() -> myModelDAO.insertInstance(myModel));
Looking like incorrect you can use Simple Thread/Threadpool/Schedulers etc
Upvotes: 1
Reputation: 1007218
All the calls into Room are from background services
Then you should not be using AsyncTask
. AsyncTask
is only for when you want to do work on the main application thread after doing background work, and that is almost never the case with a service. Use something else (thread, thread pool, RxJava, etc.). This has nothing specific to do with Room.
Upvotes: 7