当前位置: 首页>>代码示例>>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;未经允许,请勿转载。