public static <T> LiveData<RapidDocument<T>> from(final RapidDocumentReference<T> documentReference, RapidCallback.Error errorCallback) { LiveData<RapidDocument<T>> liveData = new LiveData<RapidDocument<T>>() { private RapidDocumentSubscription<T> mSubscription; @Override protected void onActive() { mSubscription = documentReference.subscribe(document -> setValue(document)).onError(errorCallback); } @Override protected void onInactive() { mSubscription.unsubscribe(); } }; return liveData; }
@MainThread public NetworkBoundResource(AppExecutors appExecutors) { this.appExecutors = appExecutors; // TODO: notify LOADING status with message? //result.setValue(Resource.loading(null)); LiveData<ResultType> dbSource = loadFromDb(); result.addSource(dbSource, data -> { result.removeSource(dbSource); if (shouldFetch(data)) { fetchFromNetwork(dbSource); } else { result.addSource(dbSource, newData -> { processData(newData); result.setValue(Resource.success(newData)); }); } }); }
@Test public void testError() { prepareRapid(false); RapidCollectionReference<Car> collection = Rapid.getInstance().collection("android_instr_test_003_" + UUID.randomUUID().toString(), Car.class); LiveData<List<RapidDocument<Car>>> liveData = RapidLiveData.from(collection, error -> { assertEquals(error.getType(), RapidError.ErrorType.PERMISSION_DENIED); unlockAsync(); }); liveData.observe(mLifecycleOwner, rapidDocuments -> { fail("Should not get any data"); unlockAsync(); }); lockAsync(); }
@Override public CallAdapter<?, ?> get(Type returnType, Annotation[] annotations, Retrofit retrofit) { if (getRawType(returnType) != LiveData.class) { return null; } Type observableType = getParameterUpperBound(0, (ParameterizedType) returnType); Class<?> rawObservableType = getRawType(observableType); if (rawObservableType != ApiResponse.class) { throw new IllegalArgumentException("type must be a resource"); } if (! (observableType instanceof ParameterizedType)) { throw new IllegalArgumentException("resource must be parameterized"); } Type bodyType = getParameterUpperBound(0, (ParameterizedType) observableType); return new LiveDataCallAdapter<>(bodyType); }
/** * Get the value from a LiveData object. We're waiting for LiveData to emit, for 2 seconds. * Once we got a notification via onChanged, we stop observing. */ public static <T> T getValue(final LiveData<T> liveData) throws InterruptedException { final Object[] data = new Object[1]; final CountDownLatch latch = new CountDownLatch(1); Observer<T> observer = new Observer<T>() { @Override public void onChanged(@Nullable T o) { data[0] = o; latch.countDown(); liveData.removeObserver(this); } }; liveData.observeForever(observer); latch.await(2, TimeUnit.SECONDS); //noinspection unchecked return (T) data[0]; }
@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"); }
public LiveData<PagedList<Organization>> getOrgsByName(String name) { return GSoCApp.getOrgDao().getOrgsByName(name) .create(null, new PagedList.Config.Builder() .setPageSize(50) .setPrefetchDistance(10) .build()); }
public LiveData<List<PhysicalData>> loadDailyData() { if (listPhysicalLiveData == null) { PhysicalData defaultData = new PhysicalData(1,"Mock",5,2, false); List<PhysicalData> list = new ArrayList<>(); list.add(defaultData); listPhysicalLiveData = new DatabaseResource<List<PhysicalData>>(list){ @NonNull @Override protected LiveData<List<PhysicalData>> loadFromDb() { return physicalDataDAO.getToday(); } }.getAsLiveData();; } return listPhysicalLiveData; }
public LiveData<Resource<List<Repo>>> loadRepos(String owner) { return new NetworkBoundResource<List<Repo>, List<Repo>>(appExecutors) { @Override protected void saveCallResult(@NonNull List<Repo> item) { repoDao.insertRepos(item); } @Override protected boolean shouldFetch(@Nullable List<Repo> data) { return data == null || data.isEmpty() || repoListRateLimit.shouldFetch(owner); } @NonNull @Override protected LiveData<List<Repo>> loadFromDb() { return repoDao.loadRepositories(owner); } @NonNull @Override protected LiveData<ApiResponse<List<Repo>>> createCall() { return githubService.getRepos(owner); } @Override protected void onFetchFailed() { repoListRateLimit.reset(owner); } }.asLiveData(); }
public LiveData<Resource<List<Artist>>> getArtistResult(String searchTerm) { return new GenericNetworkBoundResourceBuilder<List<Artist>, ArtistSearchResult>() .setAppExecutors(appExecutors) .setDbSource(artistDao.getArtists(searchTerm)) .setNetworkSource(service .getArtistSearchResult(searchTerm)) .setResultTypeShouldFetch( data -> data == null || data.isEmpty() || repoListRateLimit.shouldFetch(searchTerm)) .setNetworkRequestTypeWritetToDb(data -> artistDao.insert(data.getResults())) .setFetchFailed(() -> repoListRateLimit.reset(searchTerm)) .createGenericNetworkBoundResource().asLiveData(); }
public ProductListViewModel(Application application) { super(application); mObservableProducts = new MediatorLiveData<>(); // set by default null, until we get data from the database. mObservableProducts.setValue(null); LiveData<List<ProductEntity>> products = ((BasicApp) application).getRepository() .getProducts(); // observe the changes of the products from the database and forward them mObservableProducts.addSource(products, mObservableProducts::setValue); }
@MainThread public NetworkBoundResource(AppExecutors appExecutors) { this.appExecutors = appExecutors; result.setValue(Resource.loading(null)); LiveData<ResultType> dbSource = loadFromDb(); result.addSource(dbSource, data -> { result.removeSource(dbSource); if (shouldFetch(data)) { fetchFromNetwork(dbSource); } else { result.addSource(dbSource, newData -> setValue(Resource.success(newData))); } }); }
@MainThread public NetworkBoundResource(AppExecutors appExecutors) { this.appExecutors = appExecutors; result.setValue(Resource.loading(null)); LiveData<ResultType> dbSource = loadFromDb(); result.addSource(dbSource, data -> { result.removeSource(dbSource); if (shouldFetch(data)) { fetchFromNetwork(dbSource); } else { result.addSource(dbSource, newData -> result.setValue(Resource.success(newData))); } }); }
public LiveData<List<LocationInfo>> getLocationByUser(Context context, String user) { if (locationInfoList == null) { LocationInfoDatabase db = Room.databaseBuilder(context, LocationInfoDatabase.class, LocationDbKey.DATABASE_NAME).build(); locationInfoList = db.locationInfoDao().getLocationByUser(user); } return locationInfoList; }
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; }
@Test public void loadRepoFromNetwork() throws IOException { MutableLiveData<Repo> dbData = new MutableLiveData<>(); when(dao.load("foo", "bar")).thenReturn(dbData); Repo repo = TestUtil.createRepo("foo", "bar", "desc"); LiveData<ApiResponse<Repo>> call = successCall(repo); when(service.getRepo("foo", "bar")).thenReturn(call); LiveData<Resource<Repo>> data = repository.loadRepo("foo", "bar"); verify(dao).load("foo", "bar"); verifyNoMoreInteractions(service); Observer observer = mock(Observer.class); data.observeForever(observer); verifyNoMoreInteractions(service); verify(observer).onChanged(Resource.loading(null)); MutableLiveData<Repo> updatedDbData = new MutableLiveData<>(); when(dao.load("foo", "bar")).thenReturn(updatedDbData); dbData.postValue(null); verify(service).getRepo("foo", "bar"); verify(dao).insert(repo); updatedDbData.postValue(repo); verify(observer).onChanged(Resource.success(repo)); }
private LiveData<WeightRecord> loadWeightRecordLiveData() { WeightRecord defaultRecord = new WeightRecord(); return new DatabaseResource<WeightRecord>(defaultRecord) { @NonNull @Override protected LiveData<WeightRecord> loadFromDb() { return weightRecordDao.searchWeightRecord(); } }.getAsLiveData(); }
public PersonWidget init(AppComponent appComponent, boolean belongsToLobby, LiveData<Integer> multiWindowDividerSize, LiveData<Integer> currentFloor, LiveData<Boolean> doorsOpen) { appComponent.inject(this); this.belongsToLobby = belongsToLobby; this.multiWindowDividerSize = multiWindowDividerSize; this.currentFloor = currentFloor; this.doorsOpen = doorsOpen; return this; }
public LiveData<String> getText() { if (zkLiveData == null) { zkLiveData = new ZKLiveData(); loadNewNumber(); } return zkLiveData; }
public LiveData<List<FoodData>> loadDailyData() { if (listPhysicalLiveData == null) { FoodData defaultData = new FoodData(1,"Mock","test",false, "matin", 1.3); List<FoodData> list = new ArrayList<>(); list.add(defaultData); listPhysicalLiveData = new DatabaseResource<List<FoodData>>(list){ @NonNull @Override protected LiveData<List<FoodData>> loadFromDb() { return foodDataDao.getAllFoodToday(); } }.getAsLiveData();; } return listPhysicalLiveData; }
public LiveData<List<FoodData>> loadDailyRepasData(String repas) { if (listPhysicalLiveData == null) { FoodData defaultData = new FoodData(1,"Mock","test",false, "matin", 1.3); List<FoodData> list = new ArrayList<>(); list.add(defaultData); listPhysicalLiveData = new DatabaseResource<List<FoodData>>(list){ @NonNull @Override protected LiveData<List<FoodData>> loadFromDb() { return foodDataDao.getFoodTodayRepas(repas); } }.getAsLiveData();; } return listPhysicalLiveData; }
public LiveData<CommentData> loadSleepComment() { if (commentSleep == null) { CommentData defaultData = new CommentData(); commentSleep = new DatabaseResource<CommentData>(defaultData){ @NonNull @Override protected LiveData<CommentData> loadFromDb() { return commentDataDao.getSleepComment(); } }.getAsLiveData();; } return commentSleep; }
public LiveData<CommentData> loadWeightComment() { if (commentWeight == null) { CommentData defaultData = new CommentData(); commentWeight = new DatabaseResource<CommentData>(defaultData){ @NonNull @Override protected LiveData<CommentData> loadFromDb() { return commentDataDao.getWeightComment(); } }.getAsLiveData();; } return commentWeight; }
LiveData<Resource<Boolean>> getLiveData() { return liveData; }
@Query("SELECT * FROM Product WHERE id=:id") LiveData<Product> findById(int id);
public LiveData<List<Book>> getBooks() { return mBooks; }
/** * Exposes the latest comments so the UI can observe it */ public LiveData<List<Comment>> comments() { return commentsLiveData; }
@Override public LiveData<Product> findById(int id) { return productDao.findById(id); }
public LiveData<List<ContactNumber>> getContactNumbers() { return mContactNumbers; }
public LiveData<String> sendTransaction() { return newTransaction; }
public LiveData<User> getUser() { return user; }
public LiveData<List<Person>> getAllPersons() { return personDAO.getAllPersons(); }
LiveData<LoadMoreState> getLoadMoreStatus() { return nextPageHandler.getLoadMoreState(); }
public LiveData<List<UploadItem>> getUploadHistoryList() { return mUploadHistory; }
@Query("SELECT * FROM RepoSearchResult WHERE query = :query") public abstract LiveData<RepoSearchResult> search(String query);
@Query("SELECT * FROM Book " + "INNER JOIN Loan ON Loan.book_id LIKE Book.id " + "WHERE Loan.user_id LIKE :userId " ) LiveData<List<Book>> findBooksBorrowedByUser(String userId);
@GET("search/repositories") LiveData<ApiResponse<RepoSearchResponse>> searchRepos(@Query("q") String query);
public LiveData<ProductEntity> loadProduct(final int productId) { return mDatabase.productDao().loadProduct(productId); }
@GET("repos/{owner}/{name}/contributors") LiveData<ApiResponse<List<Contributor>>> getContributors(@Path("owner") String owner, @Path("name") String name);
@NonNull @MainThread protected abstract LiveData<ApiResponse<ResponseType>> apiCall();