|
| 1 | +package io.github.veeshostak.aichat.viewmodels; |
| 2 | + |
| 3 | +import android.app.Application; |
| 4 | +import android.arch.lifecycle.AndroidViewModel; |
| 5 | +import android.arch.lifecycle.LiveData; |
| 6 | +import android.os.AsyncTask; |
| 7 | + |
| 8 | +import java.util.List; |
| 9 | + |
| 10 | +import io.github.veeshostak.aichat.database.AppDatabase; |
| 11 | +import io.github.veeshostak.aichat.database.entity.ChatPost; |
| 12 | + |
| 13 | +/** |
| 14 | + * Created by vladshostak on 12/26/17. |
| 15 | + */ |
| 16 | + |
| 17 | +public class ListNotInRemoteChatPostsViewModel extends AndroidViewModel { |
| 18 | + |
| 19 | + private AppDatabase appDatabase; |
| 20 | + |
| 21 | + private LiveData<List<ChatPost>> notInRemoteChatPostsList; |
| 22 | + |
| 23 | + public ListNotInRemoteChatPostsViewModel(Application application) { |
| 24 | + super(application); |
| 25 | + // get instance of our db |
| 26 | + appDatabase = AppDatabase.getDatabase(this.getApplication()); |
| 27 | + // Set ChatPosts. Live Data runs the query asynchronously on a background thread |
| 28 | + notInRemoteChatPostsList = appDatabase.chatPostDao().getAllChatPostsNotInRemoteDb(); |
| 29 | + } |
| 30 | + // Live Data runs the query asynchronously on a background thread |
| 31 | + public LiveData<List<ChatPost>>getAllChatPostsNotInRemoteDb() { |
| 32 | + return appDatabase.chatPostDao().getAllChatPostsNotInRemoteDb(); |
| 33 | + } |
| 34 | + |
| 35 | + // Get chatPosts. Live Data runs the query asynchronously on a background thread |
| 36 | + public LiveData<List<ChatPost>> getData() { |
| 37 | + if (notInRemoteChatPostsList == null) { |
| 38 | + notInRemoteChatPostsList = appDatabase.chatPostDao().getAllChatPostsNotInRemoteDb(); |
| 39 | + } |
| 40 | + return notInRemoteChatPostsList; |
| 41 | + } |
| 42 | + |
| 43 | + |
| 44 | + // delete doesnt use liveData, execute in another thread. (Live Data runs the query asynchronously on a background thread when needed) |
| 45 | + public void deleteItem(ChatPost toDeleteChatPost) { |
| 46 | + new ListNotInRemoteChatPostsViewModel.DeleteAsyncTask(appDatabase).execute(toDeleteChatPost); |
| 47 | + } |
| 48 | + private static class DeleteAsyncTask extends AsyncTask<ChatPost, Void, Void> { |
| 49 | + private AppDatabase appDb; |
| 50 | + DeleteAsyncTask(AppDatabase appDatabase) { |
| 51 | + appDb = appDatabase; |
| 52 | + } |
| 53 | + @Override |
| 54 | + protected Void doInBackground(final ChatPost... params) { |
| 55 | + appDb.chatPostDao().deleteChatPosts(params[0]); |
| 56 | + return null; |
| 57 | + } |
| 58 | + } |
| 59 | + |
| 60 | + |
| 61 | +} |
0 commit comments