Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Room + AsyncTask

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);
like image 285
NickB Avatar asked Sep 29 '17 05:09

NickB


1 Answers

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.

like image 168
Phil Avatar answered Oct 19 '22 07:10

Phil