I have a Simple DAO including CRUD function
FeedEntryDAO.java
@Dao
public interface FeedEntryDAO {
@Query("SELECT * FROM feedEntrys")
LiveData<List<FeedEntry>> getAll();
@Query("SELECT * FROM feedEntrys WHERE uid = :uid LIMIT 1")
LiveData<FeedEntry> findByUid(int uid);
@Insert
void insertAll(FeedEntry... feedEntries);
@Delete
void delete(FeedEntry feedEntry);
@Update
int update(FeedEntry feedEntry);
}
For the select
, it is okay to return the LiveData type.
Inside the Activity the code is pretty for the selection
viewModel.getFeedEntrys().observe(this,entries -> {...});
However, when I try to insert, update , delete the data. The code seems a little bit ugly and also create a asynctask every time.
new AsyncTask<FeedEntry, Void, Void>() {
@Override
protected Void doInBackground(FeedEntry... feedEntries) {
viewModel.update(feedEntries[0]);
return null;
}
}.execute(feedEntry);
I have 2 question about it:
Appreciate any suggestions and advices. Thank you.
- Can i use LiveData to wrap Delete, Insert, Update calls?
No, you can't. I wrote an answer to the issue. The reason is, that LiveData is used to notify for changes. Insert, Update, Delete won't trigger a change. It will return the deleted rows, the inserted ID or the affected rows. Even if it looks horrible it makes sense not having LiveData wrapped around your stuff. Anyway, it would make sense to have something like Single around the calls to let the operation triggered and operated on a RX-Java operation.
If you want to trigger those calls, you observe on a selection query which notify your LiveData onec you have updated, inserted or deleted some/any data.
- Better way to maintain such asynctask class for delete, insert , update?
After looking at your example it looks like that you misuse the (Model/View/)ViewModel-Pattern. You should never access your repository in your view. I'm not sure if you'r doing this because its not visible in your sample. Anyway, after observing your LiveData and getting a result, there's no need to wrap the updating of data inside your viewModel in an AsyncTask. That means, that you should alway take care of
a) view <-> viewmodel <-> repository and not view <-> repository and view <-> viewmodel
and
b) don't try to use threads which are not needed. You observe LiveData on a Background Thread (@WorkerThread) by default (if not annotated with @MainThread) and get the value in the ui-thread (@MainThread).