當前位置: 首頁>>代碼示例>>Java>>正文


Java LiveData類代碼示例

本文整理匯總了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;
}
 
開發者ID:rapid-io,項目名稱:rapid-io-android,代碼行數:19,代碼來源:RapidLiveData.java

示例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));
            });
        }
    });
}
 
開發者ID:davideas,項目名稱:AndroidBlueprints,代碼行數:19,代碼來源:NetworkBoundResource.java

示例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();
}
 
開發者ID:rapid-io,項目名稱:rapid-io-android,代碼行數:17,代碼來源:LiveDataTest.java

示例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);
}
 
開發者ID:akexorcist,項目名稱:Repository-ArchComponents,代碼行數:17,代碼來源:LiveDataCallAdapterFactory.java

示例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];
}
 
開發者ID:googlecodelabs,項目名稱:android-room-with-a-view,代碼行數:21,代碼來源:LiveDataTestUtil.java

示例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");
}
 
開發者ID:googlesamples,項目名稱:android-architecture-components,代碼行數:21,代碼來源:SearchViewModelTest.java

示例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());
}
 
開發者ID:coding-blocks,項目名稱:GSoC-Info-Android,代碼行數:8,代碼來源:OrganizationViewModel.java

示例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;
}
 
開發者ID:strudelauxpommes,項目名稱:FitnessHabits,代碼行數:16,代碼來源:PhysicalRepository.java

示例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();
}
 
開發者ID:charlesng,項目名稱:SampleAppArch,代碼行數:31,代碼來源:GitRepoRepository.java

示例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();
}
 
開發者ID:charlesng,項目名稱:SampleAppArch,代碼行數:13,代碼來源:ItunesRepository.java

示例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);
}
 
開發者ID:googlesamples,項目名稱:android-architecture-components,代碼行數:14,代碼來源:ProductListViewModel.java

示例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)));
    }
  });
}
 
開發者ID:charlesng,項目名稱:SampleAppArch,代碼行數:15,代碼來源:NetworkBoundResource.java

示例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)));
        }
    });
}
 
開發者ID:akexorcist,項目名稱:Repository-ArchComponents,代碼行數:15,代碼來源:NetworkBoundResource.java

示例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;
}
 
開發者ID:akexorcist,項目名稱:Android-ArchComponents,代碼行數:9,代碼來源:MainActivityViewModel.java

示例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;
}
 
開發者ID:Jon6193,項目名稱:Android-MVVM,代碼行數:15,代碼來源:UserRepository.java


注:本文中的android.arch.lifecycle.LiveData類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。