@Inject public ConversationViewModel(InboxRepository repository) { this.conversationId = new MutableLiveData<>(); conversation = Transformations.switchMap(conversationId, input -> { if (input.isEmpty()) { return AbsentLiveData.create(); } return repository.conversation(input); }); metaData = Transformations.switchMap(conversationId, input -> { if (input.isEmpty()) { return AbsentLiveData.create(); } return repository.conversationMetaData(input); }); }
@Test public void goToNetwork() { MutableLiveData<User> dbData = new MutableLiveData<>(); when(userDao.findByLogin("foo")).thenReturn(dbData); User user = TestUtil.createUser("foo"); LiveData<ApiResponse<User>> call = ApiUtil.successCall(user); when(githubService.getUser("foo")).thenReturn(call); Observer<Resource<User>> observer = mock(Observer.class); repo.loadUser("foo").observeForever(observer); verify(githubService, never()).getUser("foo"); MutableLiveData<User> updatedDbData = new MutableLiveData<>(); when(userDao.findByLogin("foo")).thenReturn(updatedDbData); dbData.setValue(null); verify(githubService).getUser("foo"); }
@Test public void sendResultToUI() { MutableLiveData<Resource<User>> foo = new MutableLiveData<>(); MutableLiveData<Resource<User>> bar = new MutableLiveData<>(); when(userRepository.loadUser("foo")).thenReturn(foo); when(userRepository.loadUser("bar")).thenReturn(bar); Observer<Resource<User>> observer = mock(Observer.class); userViewModel.getUser().observeForever(observer); userViewModel.setLogin("foo"); verify(observer, never()).onChanged(any(Resource.class)); User fooUser = TestUtil.createUser("foo"); Resource<User> fooValue = Resource.success(fooUser); foo.setValue(fooValue); verify(observer).onChanged(fooValue); reset(observer); User barUser = TestUtil.createUser("bar"); Resource<User> barValue = Resource.success(barUser); bar.setValue(barValue); userViewModel.setLogin("bar"); verify(observer).onChanged(barValue); }
@Test public void failure() { MutableLiveData<Resource<Boolean>> liveData = enqueueResponse("foo"); pageHandler.queryNextPage("foo"); assertThat(liveData.hasActiveObservers(), is(true)); pageHandler.onChanged(Resource.error("idk", false)); assertThat(liveData.hasActiveObservers(), is(false)); assertThat(getStatus().getErrorMessage(), is("idk")); assertThat(getStatus().getErrorMessageIfNotHandled(), is("idk")); assertThat(getStatus().getErrorMessageIfNotHandled(), nullValue()); assertThat(getStatus().isRunning(), is(false)); assertThat(pageHandler.hasMore, is(true)); reset(repository); MutableLiveData<Resource<Boolean>> liveData2 = enqueueResponse("foo"); pageHandler.queryNextPage("foo"); assertThat(liveData2.hasActiveObservers(), is(true)); assertThat(getStatus().isRunning(), is(true)); pageHandler.onChanged(Resource.success(false)); assertThat(getStatus().isRunning(), is(false)); assertThat(getStatus().getErrorMessage(), is(nullValue())); assertThat(pageHandler.hasMore, is(false)); }
@Inject public RepoViewModel(RepoRepository repository) { this.repoId = new MutableLiveData<>(); repo = Transformations.switchMap(repoId, input -> { if (input.isEmpty()) { return AbsentLiveData.create(); } return repository.loadRepo(input.owner, input.name); }); contributors = Transformations.switchMap(repoId, input -> { if (input.isEmpty()) { return AbsentLiveData.create(); } else { return repository.loadContributors(input.owner, input.name); } }); }
@Test public void search_fromDb() { List<Integer> ids = Arrays.asList(1, 2); Observer<Resource<List<Repo>>> observer = mock(Observer.class); MutableLiveData<RepoSearchResult> dbSearchResult = new MutableLiveData<>(); MutableLiveData<List<Repo>> repositories = new MutableLiveData<>(); when(dao.search("foo")).thenReturn(dbSearchResult); repository.search("foo").observeForever(observer); verify(observer).onChanged(Resource.loading(null)); verifyNoMoreInteractions(service); reset(observer); RepoSearchResult dbResult = new RepoSearchResult("foo", ids, 2, null); when(dao.loadOrdered(ids)).thenReturn(repositories); dbSearchResult.postValue(dbResult); List<Repo> repoList = new ArrayList<>(); repositories.postValue(repoList); verify(observer).onChanged(Resource.success(repoList)); verifyNoMoreInteractions(service); }
@Test public void swap() { LiveData<Resource<Boolean>> nextPage = new MutableLiveData<>(); when(repository.searchNextPage("foo")).thenReturn(nextPage); Observer<Resource<List<Repo>>> result = mock(Observer.class); viewModel.getResults().observeForever(result); verifyNoMoreInteractions(repository); viewModel.setQuery("foo"); verify(repository).search("foo"); viewModel.loadNextPage(); viewModel.getLoadMoreStatus().observeForever(mock(Observer.class)); verify(repository).searchNextPage("foo"); assertThat(nextPage.hasActiveObservers(), is(true)); viewModel.setQuery("bar"); assertThat(nextPage.hasActiveObservers(), is(false)); verify(repository).search("bar"); verify(repository, never()).searchNextPage("bar"); }
@Before public void setup() throws Exception { // init realm database mockRealmDatabase = PowerMockito.mock(RealmDatabase.class); // ============ init user data store ============== mUser = sampleUser(1L); // noinspection unchecked mMockUserLiveData = PowerMockito.mock(MutableLiveData.class); mockUserDataStore = PowerMockito.mock(UserDataStore.class); when(mockUserDataStore.getUserLiveData()).thenReturn(mMockUserLiveData); // ============ init test component =================== testComponent = DaggerTestComponent.builder() .dataModule(new DataModule(mockRealmDatabase, mockUserDataStore)) .build(); inject(testComponent); }
@MainThread @NonNull LiveData<Response<List<Country>>> getMoviesList() { if (countriesLiveData == null) { countriesLiveData = new MutableLiveData<>(); countriesRepository.getCountries() .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .doOnSubscribe(disposable -> loadingLiveData.setValue(true)) .doAfterTerminate(() -> loadingLiveData.setValue(false)) .subscribe( countries1 -> countriesLiveData.setValue(Response.success(countries1)), throwable -> countriesLiveData.setValue(Response.error(throwable)) ); } return countriesLiveData; }
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_live_data); tvUsername = findViewById(R.id.tv_username); username = new MutableLiveData<>(); username.observe(this, new Observer<String>() { @Override public void onChanged(@Nullable String s) { tvUsername.setText(s); } }); }
/** * Subscribes to the entity states of the given type. * * <p>The method returns a {@link LiveData} of map (string ID -> entity state). The ID is * the {@linkplain io.spine.Identifier#toString(Object) string representation} of * the corresponding entity ID. * * <p>Currently, the element removal is not supported. If a {@link DocumentChange} of type other * than {@link DocumentChange.Type#ADDED ADDED} or {@link DocumentChange.Type#MODIFIED MODIFIED} * is encountered, an {@link UnsupportedOperationException} is thrown. * * @param targetType the class of the entity to subscribe to * @param <T> the type of the entity to subscribe to * @return an instance of {@link LiveData} for the observers to subscribe to */ public <T extends Message> LiveData<Map<String, T>> subscribeTo(Class<T> targetType) { checkNotNull(targetType); final CollectionReference targetCollection = collectionFor(targetType); final MutableLiveData<Map<String, T>> result = new MutableLiveData<>(); targetCollection.addSnapshotListener((documentSnapshots, error) -> { if (error != null) { final String errorMsg = format( "Error encountered while listening for the %s state updates.", targetType ); Log.e(TAG, errorMsg, error); } else { final Parser<T> parser = getParserFor(targetType); for (DocumentChange change : documentSnapshots.getDocumentChanges()) { deliverUpdate(change, result, parser); } } }); return result; }
/** * Subscribes to the single entity state of the given type. * * <p>If multiple records of the given type are found in Firestore, * an {@link IllegalStateException} is thrown. * * <p>If no records of the given type are found in Firestore, the update is ignored (i.e. * the resulting {@link LiveData} is not triggered). * * <p>Currently, the element removal is not supported. If a {@link DocumentChange} of type other * than {@link DocumentChange.Type#ADDED ADDED} or {@link DocumentChange.Type#MODIFIED MODIFIED} * is encountered, an {@link UnsupportedOperationException} is thrown. * * @param targetType the class of the entity state to subscribe to * @param <T> the type of the entity state to subscribe to * @return a instance of {@link LiveData} for the observers to subscribe to */ @SuppressWarnings("UnnecessaryReturnStatement") // OK for a fast exit on invalid data. public <T extends Message> LiveData<T> subscribeToSingle(Class<T> targetType) { final MutableLiveData<T> liveData = new MutableLiveData<>(); final LiveData<Map<String, T>> allRecordsData = subscribeTo(targetType); allRecordsData.observeForever(map -> { if (map == null || map.isEmpty()) { return; } else if (map.size() > 1) { throw newIllegalStateException("Type %s has multiple instances.", targetType); } else { final Map.Entry<?, T> singleEntry = map.entrySet() .iterator() .next(); final T singleData = singleEntry.getValue(); liveData.postValue(singleData); } }); return liveData; }
/** * Delivers the entity state update represented by the given {@link DocumentChange} to * the observers of the given {@link LiveData}. * * @param change the Firestore document change * @param destination the {@link LiveData} publishing the update * @param parser the {@link Parser} for the target entity state type * @param <T> the entity state type */ private static <T extends Message> void deliverUpdate(DocumentChange change, MutableLiveData<Map<String, T>> destination, Parser<T> parser) { final DocumentChange.Type type = change.getType(); final Map<String, T> currentData = destination.getValue(); final Map<String, T> newData = currentData == null ? newHashMap() : newHashMap(currentData); final DocumentSnapshot doc = change.getDocument(); final String id = parseMessageId(doc); final T newMessage = parseMessage(doc, parser); if (type == ADDED || type == MODIFIED) { newData.put(id, newMessage); } else { throw newIllegalArgumentException("Unexpected document change: %s", type.toString()); } destination.postValue(newData); }
private LiveData<List<PostsListBean>> handleData(final int offset) { final MutableLiveData<List<PostsListBean>> liveData = new MutableLiveData<>(); Disposable subscribe = mRetrofit.create(IApi.class).getPostsList(mSlug, offset) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Consumer<List<PostsListBean>>() { @Override public void accept(@io.reactivex.annotations.NonNull List<PostsListBean> list) throws Exception { mList.addAll(list); liveData.setValue(mList); } }, new ErrorAction() { @Override public void doAction() { liveData.setValue(null); } }.action()); mDisposable.add(subscribe); mIsLoading.setValue(false); return liveData; }
public MutableLiveData<HotMovieBean> getHotMovie() { final MutableLiveData<HotMovieBean> data = new MutableLiveData<>(); HttpClient.Builder.getDouBanService().getHotMovie().subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<HotMovieBean>() { @Override public void onCompleted() { } @Override public void onError(Throwable e) { data.setValue(null); } @Override public void onNext(HotMovieBean hotMovieBean) { if (hotMovieBean != null) { data.setValue(hotMovieBean); } } }); return data; }
public CollectionViewModel(Application application) { super(application); // initialize LiveData mStationListLiveData = new MutableLiveData<ArrayList<Station>>(); mPlayerServiceStationLiveData = new MutableLiveData<Station>(); mTwoPaneLiveData = new MutableLiveData<Boolean>(); // load state from shared preferences and set live data values loadAppState(application); // set station from PlayerService to null mPlayerServiceStationLiveData.setValue(null); // load station list from storage and set live data mStationListLiveData.setValue(StationListHelper.loadStationListFromStorage(application)); // load station list and set live data in background -> not used because DiffResult.dispatchUpdatesTo is causing problems in Adapter // new LoadCollectionAsyncTask().execute(application); }
public FlexibleViewModel() { identifier = new MutableLiveData<>(); liveItems = Transformations.switchMap(identifier, new Function<Identifier, LiveData<List<AdapterItem>>>() { @Override public LiveData<List<AdapterItem>> apply(Identifier input) { return Transformations.map(getSource(input), new Function<Source, List<AdapterItem>>() { @Override public List<AdapterItem> apply(Source source) { if (isSourceValid(source)) { return map(source); } else { return liveItems.getValue(); } } }); } }); }
LiveData<Long> insert(@NonNull Context context, @NonNull final ChosenPhoto chosenPhoto, @Nullable final String callingApplication) { final MutableLiveData<Long> asyncInsert = new MutableLiveData<>(); if (persistUriAccess(context, chosenPhoto)) { new Thread() { @Override public void run() { long id = insertInternal(chosenPhoto); if (id != 0L && callingApplication != null) { Metadata metadata = new Metadata(ChosenPhoto.getContentUri(id)); metadata.date = new Date(); metadata.location = context.getString(R.string.gallery_shared_from, callingApplication); GalleryDatabase.getInstance(context).metadataDao().insert(metadata); } asyncInsert.postValue(id); } }.start(); } else { asyncInsert.setValue(0L); } return asyncInsert; }
public MutableLiveData<Resource<List<SoccerSeasonModel>>> getResults() { if (results != null) { // TODO: 2017/11/16 Memory Cache return results; } else { results = new MutableLiveData<>(); } getDataTest.execute(new GetSoccerSeasion(),null); return results; }
public MutableLiveData<Resource<List<TeamModel>>> getResults(int idSeason) { if (results != null) { // TODO: 2017/11/16 Memory Cache return results; } else { results = new MutableLiveData<>(); } getTeamUseCase.execute(new GetTeam(),idSeason); return results; }
public LiveData<ApiResponse<LoginBean>> getLogin(String email, String password) { MutableLiveData<ApiResponse<LoginBean>> liveData = new MutableLiveData<>(); LoginBean loginBean = new LoginBean(email, "MyCompany"); loginBean.setIsLogin(1); liveData.setValue(new ApiResponse<>(Response.success(loginBean))); return liveData; }
public LiveData<ApiResponse<LoginBean>> getLogin(String email, String password) { MutableLiveData<ApiResponse<LoginBean>> liveData = new MutableLiveData<>(); LoginBean loginBean = new LoginBean(email, "Facebook"); loginBean.setIsLogin(1); liveData.setValue(new ApiResponse<>(Response.success(loginBean))); return liveData; }
public LiveData<ApiResponse<LoginBean>> getLogin(String email, String password) { MutableLiveData<ApiResponse<LoginBean>> liveData = new MutableLiveData<>(); LoginBean loginBean = new LoginBean(email, "Google"); loginBean.setIsLogin(1); liveData.setValue(new ApiResponse<>(Response.success(loginBean))); return liveData; }
public void init() { messageContainerA = new MutableLiveData<>(); messageContainerA.setValue("Default Message"); messageContainerB = new MutableLiveData<>(); messageContainerB.setValue("Default Message"); }
public LiveData<User> getUser(String email) { MutableLiveData<User> liveData = new MutableLiveData<>(); userDao.loadUser(email) .compose(transformers.applySchedulersToFlowable()) .subscribe(liveData::setValue, Timber::d); userApi.getUser(email) .compose(transformers.applySchedulersToFlowable()) .map(mapper::toEntity) .subscribe(userDao::saveUser, Timber::d); return liveData; }
public LiveData<List<User>> getUsers() { MutableLiveData<List<User>> liveData = new MutableLiveData<>(); userDao.loadUsers() .compose(transformers.applySchedulersToFlowable()) .subscribe(liveData::setValue, Timber::d); userApi.getUsers() .compose(transformers.applySchedulersToFlowable()) .flatMapIterable(users -> users) .map(mapper::toEntity) .subscribe(userDao::saveUser, Timber::d); return liveData; }
public LiveData<Boolean> saveUser(User user) { MutableLiveData<Boolean> liveData = new MutableLiveData<>(); Completable.fromAction(() -> userDao.saveUser(user)) .compose(transformers.applySchedulersToCompletable()) .subscribe(() -> liveData.setValue(true), throwable -> { Timber.d(throwable); liveData.setValue(false); }); return liveData; }
/** * Creates a computable live data which is computed when there are active observers. * <p> * It can also be invalidated via {@link #invalidate()} which will result in a call to * {@link #compute()} if there are active observers (or when they start observing) */ @SuppressWarnings("WeakerAccess") public RealmComputableLiveData(RealmPaginationManager realmPaginationManager) { this.realmPaginationManager = realmPaginationManager; this.realmQueryExecutor = realmPaginationManager.getRealmQueryExecutor(); mLiveData = new MutableLiveData<T>() { @Override protected void onActive() { realmQueryExecutor.execute(mRefreshRunnable); } }; }
@Override protected LiveData<LogcatContent> loadFromDb() { if (checkId()) { return logcatDao.queryLogcatContent(id); } return new MutableLiveData<>(); }
@Test public void dbSuccessWithFetchFailure() { Foo dbValue = new Foo(1); AtomicBoolean saved = new AtomicBoolean(false); shouldFetch = (foo) -> foo == dbValue; saveCallResult = foo -> { saved.set(true); return null; }; ResponseBody body = ResponseBody.create(MediaType.parse("text/html"), "error"); MutableLiveData<ApiResponse<Foo>> apiResponseLiveData = new MutableLiveData(); createCall = (aVoid) -> apiResponseLiveData; Observer<Resource<Foo>> observer = Mockito.mock(Observer.class); networkBoundResource.asLiveData().observeForever(observer); drain(); verify(observer).onChanged(Resource.loading(null)); reset(observer); dbData.setValue(dbValue); drain(); verify(observer).onChanged(Resource.loading(dbValue)); apiResponseLiveData.setValue(new ApiResponse<>(Response.error(400, body))); drain(); assertThat(saved.get(), is(false)); verify(observer).onChanged(Resource.error("error", dbValue)); Foo dbValue2 = new Foo(2); dbData.setValue(dbValue2); drain(); verify(observer).onChanged(Resource.error("error", dbValue2)); verifyNoMoreInteractions(observer); }
@Test public void dbSuccessWithReFetchSuccess() { Foo dbValue = new Foo(1); Foo dbValue2 = new Foo(2); AtomicReference<Foo> saved = new AtomicReference<>(); shouldFetch = (foo) -> foo == dbValue; saveCallResult = foo -> { saved.set(foo); dbData.setValue(dbValue2); return null; }; MutableLiveData<ApiResponse<Foo>> apiResponseLiveData = new MutableLiveData(); createCall = (aVoid) -> apiResponseLiveData; Observer<Resource<Foo>> observer = Mockito.mock(Observer.class); networkBoundResource.asLiveData().observeForever(observer); drain(); verify(observer).onChanged(Resource.loading(null)); reset(observer); dbData.setValue(dbValue); drain(); final Foo networkResult = new Foo(1); verify(observer).onChanged(Resource.loading(dbValue)); apiResponseLiveData.setValue(new ApiResponse<>(Response.success(networkResult))); drain(); assertThat(saved.get(), is(networkResult)); verify(observer).onChanged(Resource.success(dbValue2)); verifyNoMoreInteractions(observer); }
public LiveData<User> getUser(long userId) { final MutableLiveData<User> mutableLiveData = new MutableLiveData<User>(); new android.os.Handler().post(new Runnable() { @Override public void run() { mutableLiveData.setValue(new User()); } }); return mutableLiveData; }
LiveData<QueueItem> getQueueItem() { if (queueItem == null) { queueItem = new MutableLiveData<>(); loadData(); } return queueItem; }
@Test public void dontGoToNetwork() { MutableLiveData<User> dbData = new MutableLiveData<>(); User user = TestUtil.createUser("foo"); dbData.setValue(user); when(userDao.findByLogin("foo")).thenReturn(dbData); Observer<Resource<User>> observer = mock(Observer.class); repo.loadUser("foo").observeForever(observer); verify(githubService, never()).getUser("foo"); verify(observer).onChanged(Resource.success(user)); }