|
| 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.ArrayList; |
| 9 | +import java.util.List; |
| 10 | + |
| 11 | +import io.github.veeshostak.aichat.database.AppDatabase; |
| 12 | +import io.github.veeshostak.aichat.database.dao.ChatPostDao; |
| 13 | +import io.github.veeshostak.aichat.database.entity.ChatPost; |
| 14 | + |
| 15 | +/** |
| 16 | + * Created by vladshostak on 12/26/17. |
| 17 | + */ |
| 18 | + |
| 19 | +/* |
| 20 | +
|
| 21 | +ViewModels do not contain code related to the UI. This helps in the decoupling of our app components. |
| 22 | +In Room, the database instance should ideally be contained in a ViewModel rather than on the Activity/Fragment. |
| 23 | +
|
| 24 | +ViewModels are entities that are free of the Activity/Fragment lifecycle. |
| 25 | +For example, they can retain their state/data even during an orientation change. |
| 26 | +*/ |
| 27 | + |
| 28 | +// If your ViewModel needs the application context, it must extend AndroidViewModel, else extend ViewModel |
| 29 | +public class ListAllChatPostsViewModel extends AndroidViewModel { |
| 30 | + |
| 31 | + private LiveData<List<ChatPost>> chatPostList; |
| 32 | + |
| 33 | + private AppDatabase appDatabase; |
| 34 | + |
| 35 | + public ListAllChatPostsViewModel(Application application) { |
| 36 | + super(application); |
| 37 | + // get instance of our db |
| 38 | + appDatabase = AppDatabase.getDatabase(this.getApplication()); |
| 39 | + // Set ChatPosts. Live Data runs the query asynchronously on a background thread |
| 40 | + chatPostList = appDatabase.chatPostDao().getAllChatPosts(); |
| 41 | + } |
| 42 | + |
| 43 | + // Get chatPosts. Live Data runs the query asynchronously on a background thread |
| 44 | + public LiveData<List<ChatPost>> getData() { |
| 45 | + if (chatPostList == null) { |
| 46 | + chatPostList = appDatabase.chatPostDao().getAllChatPosts(); |
| 47 | + } |
| 48 | + return chatPostList; |
| 49 | + } |
| 50 | + |
| 51 | + |
| 52 | + // delete doesnt use liveData, execute in another thread. (Live Data runs the query asynchronously on a background thread when needed) |
| 53 | + public void deleteItem(ChatPost toDeleteChatPost) { |
| 54 | + new DeleteAsyncTask(appDatabase).execute(toDeleteChatPost); |
| 55 | + } |
| 56 | + private static class DeleteAsyncTask extends AsyncTask<ChatPost, Void, Void> { |
| 57 | + private AppDatabase appDb; |
| 58 | + DeleteAsyncTask(AppDatabase appDatabase) { |
| 59 | + appDb = appDatabase; |
| 60 | + } |
| 61 | + @Override |
| 62 | + protected Void doInBackground(final ChatPost... params) { |
| 63 | + appDb.chatPostDao().deleteChatPosts(params[0]); |
| 64 | + return null; |
| 65 | + } |
| 66 | + } |
| 67 | + |
| 68 | + |
| 69 | +} |
| 70 | + |
0 commit comments