本文整理汇总了Java中android.arch.lifecycle.LiveData类的典型用法代码示例。如果您正苦于以下问题:Java LiveData类的具体用法?Java LiveData怎么用?Java LiveData使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
LiveData类属于android.arch.lifecycle包,在下文中一共展示了LiveData类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: from
import android.arch.lifecycle.LiveData; //导入依赖的package包/类
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;
}
示例2: NetworkBoundResource
import android.arch.lifecycle.LiveData; //导入依赖的package包/类
@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));
});
}
});
}
示例3: testError
import android.arch.lifecycle.LiveData; //导入依赖的package包/类
@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();
}
示例4: get
import android.arch.lifecycle.LiveData; //导入依赖的package包/类
@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);
}
示例5: getValue
import android.arch.lifecycle.LiveData; //导入依赖的package包/类
/**
* 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];
}
示例6: swap
import android.arch.lifecycle.LiveData; //导入依赖的package包/类
@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");
}
示例7: getOrgsByName
import android.arch.lifecycle.LiveData; //导入依赖的package包/类
public LiveData<PagedList<Organization>> getOrgsByName(String name) {
return GSoCApp.getOrgDao().getOrgsByName(name)
.create(null, new PagedList.Config.Builder()
.setPageSize(50)
.setPrefetchDistance(10)
.build());
}
示例8: loadDailyData
import android.arch.lifecycle.LiveData; //导入依赖的package包/类
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;
}
示例9: loadRepos
import android.arch.lifecycle.LiveData; //导入依赖的package包/类
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();
}
示例10: getArtistResult
import android.arch.lifecycle.LiveData; //导入依赖的package包/类
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();
}
示例11: ProductListViewModel
import android.arch.lifecycle.LiveData; //导入依赖的package包/类
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);
}
示例12: NetworkBoundResource
import android.arch.lifecycle.LiveData; //导入依赖的package包/类
@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)));
}
});
}
示例13: NetworkBoundResource
import android.arch.lifecycle.LiveData; //导入依赖的package包/类
@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)));
}
});
}
示例14: getLocationByUser
import android.arch.lifecycle.LiveData; //导入依赖的package包/类
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;
}
示例15: getUser
import android.arch.lifecycle.LiveData; //导入依赖的package包/类
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;
}