package ml.docilealligator.infinityforreddit.subscribedsubreddit; import android.app.Application; import androidx.annotation.NonNull; import androidx.lifecycle.LiveData; import androidx.lifecycle.MutableLiveData; import androidx.lifecycle.Transformations; import androidx.lifecycle.ViewModel; import androidx.lifecycle.ViewModelProvider; import java.util.List; import ml.docilealligator.infinityforreddit.RedditDataRoomDatabase; public class SubscribedSubredditViewModel extends ViewModel { private final SubscribedSubredditRepository mSubscribedSubredditRepository; private final LiveData> mAllSubscribedSubreddits; private final LiveData> mAllFavoriteSubscribedSubreddits; private final MutableLiveData searchQueryLiveData; public SubscribedSubredditViewModel(RedditDataRoomDatabase redditDataRoomDatabase, String accountName) { mSubscribedSubredditRepository = new SubscribedSubredditRepository(redditDataRoomDatabase, accountName); searchQueryLiveData = new MutableLiveData<>(""); mAllSubscribedSubreddits = Transformations.switchMap(searchQueryLiveData, searchQuery -> mSubscribedSubredditRepository.getAllSubscribedSubredditsWithSearchQuery(searchQuery)); mAllFavoriteSubscribedSubreddits = Transformations.switchMap(searchQueryLiveData, searchQuery -> mSubscribedSubredditRepository.getAllFavoriteSubscribedSubredditsWithSearchQuery(searchQuery)); } public LiveData> getAllSubscribedSubreddits() { return mAllSubscribedSubreddits; } public LiveData> getAllFavoriteSubscribedSubreddits() { return mAllFavoriteSubscribedSubreddits; } public void insert(SubscribedSubredditData subscribedSubredditData) { mSubscribedSubredditRepository.insert(subscribedSubredditData); } public void setSearchQuery(String searchQuery) { searchQueryLiveData.postValue(searchQuery); } public static class Factory extends ViewModelProvider.NewInstanceFactory { private final RedditDataRoomDatabase mRedditDataRoomDatabase; private final String mAccountName; public Factory(RedditDataRoomDatabase redditDataRoomDatabase, String accountName) { this.mRedditDataRoomDatabase = redditDataRoomDatabase; this.mAccountName = accountName; } @NonNull @Override public T create(@NonNull Class modelClass) { return (T) new SubscribedSubredditViewModel(mRedditDataRoomDatabase, mAccountName); } } }