Java 类android.arch.lifecycle.LiveData 实例源码

项目:rapid-io-android    文件:RapidLiveData.java   
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;
}
项目:AndroidBlueprints    文件:NetworkBoundResource.java   
@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));
            });
        }
    });
}
项目:rapid-io-android    文件:LiveDataTest.java   
@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();
}
项目:Repository-ArchComponents    文件:LiveDataCallAdapterFactory.java   
@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);
}
项目:android-room-with-a-view    文件:LiveDataTestUtil.java   
/**
 * 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];
}
项目:android-architecture-components    文件:SearchViewModelTest.java   
@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");
}
项目:GSoC-Info-Android    文件:OrganizationViewModel.java   
public LiveData<PagedList<Organization>> getOrgsByName(String name) {
    return GSoCApp.getOrgDao().getOrgsByName(name)
            .create(null, new PagedList.Config.Builder()
                    .setPageSize(50)
                    .setPrefetchDistance(10)
                    .build());
}
项目:FitnessHabits    文件:PhysicalRepository.java   
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;
}
项目:SampleAppArch    文件:GitRepoRepository.java   
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();
}
项目:SampleAppArch    文件:ItunesRepository.java   
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();
}
项目:android-architecture-components    文件:ProductListViewModel.java   
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);
}
项目:SampleAppArch    文件:NetworkBoundResource.java   
@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)));
    }
  });
}
项目:Repository-ArchComponents    文件:NetworkBoundResource.java   
@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)));
        }
    });
}
项目:Android-ArchComponents    文件:MainActivityViewModel.java   
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;
}
项目:Android-MVVM    文件:UserRepository.java   
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;
}
项目:android-architecture-components    文件:RepoRepositoryTest.java   
@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));
}
项目:FitnessHabits    文件:WeightRepository.java   
private LiveData<WeightRecord> loadWeightRecordLiveData() {

        WeightRecord defaultRecord = new WeightRecord();

        return new DatabaseResource<WeightRecord>(defaultRecord) {
            @NonNull
            @Override
            protected LiveData<WeightRecord> loadFromDb() {
                return weightRecordDao.searchWeightRecord();
            }
        }.getAsLiveData();

    }
项目:elevator-room    文件:PersonWidget.java   
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;
}
项目:JueDiQiuSheng    文件:ZKViewModule.java   
public LiveData<String> getText() {
    if (zkLiveData == null) {
        zkLiveData = new ZKLiveData();
        loadNewNumber();
    }
    return zkLiveData;
}
项目:FitnessHabits    文件:FoodDataRepository.java   
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;
}
项目:FitnessHabits    文件:FoodDataRepository.java   
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;
}
项目:FitnessHabits    文件:CommentDataRepository.java   
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;
}
项目:FitnessHabits    文件:CommentDataRepository.java   
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;
}
项目:android-architecture-components    文件:FetchNextSearchPageTask.java   
LiveData<Resource<Boolean>> getLiveData() {
    return liveData;
}
项目:RoomDagger2Demo    文件:ProductDao.java   
@Query("SELECT * FROM Product WHERE id=:id")
LiveData<Product> findById(int id);
项目:android-persistence    文件:TypeConvertersViewModel.java   
public LiveData<List<Book>> getBooks() {
    return mBooks;
}
项目:OfflineSampleApp    文件:CommentsViewModel.java   
/**
 * Exposes the latest comments so the UI can observe it
 */
public LiveData<List<Comment>> comments() {
    return commentsLiveData;
}
项目:RoomDagger2Demo    文件:ProductDataSource.java   
@Override
public LiveData<Product> findById(int id) {
    return productDao.findById(id);
}
项目:lead-management-android    文件:EditContactActivityViewModel.java   
public LiveData<List<ContactNumber>> getContactNumbers() {
    return mContactNumbers;
}
项目:trust-wallet-android    文件:ConfirmationViewModel.java   
public LiveData<String> sendTransaction() {
    return newTransaction;
}
项目:JueDiQiuSheng    文件:UserProfileViewModel.java   
public LiveData<User> getUser() {
    return user;
}
项目:AndroidRoom    文件:PersonRepository.java   
public LiveData<List<Person>> getAllPersons() {
    return personDAO.getAllPersons();
}
项目:firebase-chat-android-architecture-components    文件:InboxViewModel.java   
LiveData<LoadMoreState> getLoadMoreStatus() {
    return nextPageHandler.getLoadMoreState();
}
项目:file.io-app    文件:UploadItemViewModel.java   
public LiveData<List<UploadItem>> getUploadHistoryList() {
    return mUploadHistory;
}
项目:android-architecture-components    文件:RepoDao.java   
@Query("SELECT * FROM RepoSearchResult WHERE query = :query")
public abstract LiveData<RepoSearchResult> search(String query);
项目:android-persistence    文件:BookDao.java   
@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);
项目:android-architecture-components    文件:GithubService.java   
@GET("search/repositories")
LiveData<ApiResponse<RepoSearchResponse>> searchRepos(@Query("q") String query);
项目:android-architecture-components    文件:DataRepository.java   
public LiveData<ProductEntity> loadProduct(final int productId) {
    return mDatabase.productDao().loadProduct(productId);
}
项目:SampleAppArch    文件:GithubService.java   
@GET("repos/{owner}/{name}/contributors")
LiveData<ApiResponse<List<Contributor>>> getContributors(@Path("owner") String owner,
    @Path("name") String name);
项目:AndroidBlueprints    文件:NetworkBoundResource.java   
@NonNull
@MainThread
protected abstract LiveData<ApiResponse<ResponseType>> apiCall();