本文整理匯總了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;
}