Recently I'm learning to use DAO. From what I understand, all the @Insert
, @Update
, or @Query
are executed asynchronously. And from the documentary, @Insert
can return a long
value, which is the new rowId
for the inserted item (or List<long>
if multiple items). Assuming my DAO looks like this:
@Insert
long insertTransaction(Transaction transaction);
@Insert
List<Long> insertTransactions(List<Transaction> transactions);
When I use these methods in an activity or fragment, does it mean I get the long value after the async task is completed?
<!-- language: lang-none -->
// Do I get 0 if the insert is not complete
// or it will wait till the insert is complete and return long?
long id = viewModel.insertTransaction(transaction)
If it waits for the async task to finish, won't it block the main thread (especially when inserting large lists)? And if not, how do I check if the insert is finished?
From what I understand, all the @Insert, @Update, or @Query are executed asynchronously.
By default all the @Insert, @Update, or @Query are executed synchronously. Room warns you about that and you cannot do sync calls without explicit using method allowMainThreadQueries in RoomDatabase.Builder.
Of course, it's not recommended to use synchronous calls. To use async calls you have several options (look at official documentation):
suspend
keyword)Single
, Maybe
, Completable
)ListenableFuture
).In addition you can move DB operations to background thread explicitly using Threads/ThreadPools and to manage asynchronous work by yourself (using callbacks, for example).
Using one of options above you'll be notified when async task is over (notification's method depends on framework you've chosen). Otherwise you make sync call and block UI thread.