Issue
As discussed here Android Room - Get the id of new inserted row with auto-generate it is possible to get the ID from the newly inserted object.
But how do I get this ID all the way from the DAO to my Activity class in an MVVM pattern?
Some answers on there suggest using rxjava and something like this:
return Single.fromCallable<Long> { recipesDao.insertManual(cookingRecipes) }
But does it make sense to implement two whole Gradle dependencies just to have one method call?
Isn't there a way to make this work with my current structure?
Activity - ViewModel - Repository ( - AsyncTask) - Dao
The only problem is getting the return value from the insert statement, which is called from an AsyncTask
:
private static class UpdateChallengeInfosAsyncTask extends AsyncTask<ChallengeInfos, Void, Void> {
private ChallengeInfosDao mAsyncTaskDao;
UpdateChallengeInfosAsyncTask(ChallengeInfosDao dao) {
mAsyncTaskDao = dao;
}
@Override
protected Void doInBackground(ChallengeInfos... challengeInfos) {
mAsyncTaskDao.insert(challengeInfos[0]);
return null;
}
}
Maybe it's possible with a onPostExecute()
+ Interface
combo like here?
How to get the result of OnPostExecute() to main activity because AsyncTask is a separate class?
Solution
Okay so what I ended up doing and what seems to be working pretty well is this:
Basically used the structure from this answer:
https://stackoverflow.com/a/12575319/1972372
And implemented the AsynTask
callback-interface in my ViewModel
with a MutableLiveData
object for the Activity to call once in the beginning and hang on to until it is updated once:
public class ChallengeViewModel extends AndroidViewModel implements ChallengesRepository.UpdateChallengeInfosAsyncTask.AsyncResponse {
private MutableLiveData<Integer> insertedChlgInfoID;
....
....
public void insertChallengeInfos(ChallengeInfos challengeInfos) {
mRepository.insertChallengeInfos(challengeInfos, this);
}
public LiveData<Integer> getInsertedChlgInfoID() {
return insertedChlgInfoID;
}
@Override
public void processFinish(Long result) {
insertedChlgInfoID.setValue(Ints.checkedCast(result));
}
}
I understand the reasons why AsyncTask
may be called bad in certain scenarios, but I think in my case it really works fine and doesn't really have any potential risks of memory leaks or similar, since it's only very basic write operations. And rewriting the whole logic doesn't seem to be of any benefit for my case.
Answered By - Big_Chair
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.