本文整理匯總了Java中android.arch.lifecycle.MutableLiveData類的典型用法代碼示例。如果您正苦於以下問題:Java MutableLiveData類的具體用法?Java MutableLiveData怎麽用?Java MutableLiveData使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。
MutableLiveData類屬於android.arch.lifecycle包,在下文中一共展示了MutableLiveData類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。
示例1: failure
import android.arch.lifecycle.MutableLiveData; //導入依賴的package包/類
@Test
public void failure() {
MutableLiveData<Resource<Boolean>> liveData = enqueueResponse("foo");
pageHandler.queryNextPage("foo");
assertThat(liveData.hasActiveObservers(), is(true));
pageHandler.onChanged(Resource.error("idk", false));
assertThat(liveData.hasActiveObservers(), is(false));
assertThat(getStatus().getErrorMessage(), is("idk"));
assertThat(getStatus().getErrorMessageIfNotHandled(), is("idk"));
assertThat(getStatus().getErrorMessageIfNotHandled(), nullValue());
assertThat(getStatus().isRunning(), is(false));
assertThat(pageHandler.hasMore, is(true));
reset(repository);
MutableLiveData<Resource<Boolean>> liveData2 = enqueueResponse("foo");
pageHandler.queryNextPage("foo");
assertThat(liveData2.hasActiveObservers(), is(true));
assertThat(getStatus().isRunning(), is(true));
pageHandler.onChanged(Resource.success(false));
assertThat(getStatus().isRunning(), is(false));
assertThat(getStatus().getErrorMessage(), is(nullValue()));
assertThat(pageHandler.hasMore, is(false));
}
示例2: ConversationViewModel
import android.arch.lifecycle.MutableLiveData; //導入依賴的package包/類
@Inject
public ConversationViewModel(InboxRepository repository) {
this.conversationId = new MutableLiveData<>();
conversation = Transformations.switchMap(conversationId, input -> {
if (input.isEmpty()) {
return AbsentLiveData.create();
}
return repository.conversation(input);
});
metaData = Transformations.switchMap(conversationId, input -> {
if (input.isEmpty()) {
return AbsentLiveData.create();
}
return repository.conversationMetaData(input);
});
}
開發者ID:hbmartin,項目名稱:firebase-chat-android-architecture-components,代碼行數:19,代碼來源:ConversationViewModel.java
示例3: goToNetwork
import android.arch.lifecycle.MutableLiveData; //導入依賴的package包/類
@Test
public void goToNetwork() {
MutableLiveData<User> dbData = new MutableLiveData<>();
when(userDao.findByLogin("foo")).thenReturn(dbData);
User user = TestUtil.createUser("foo");
LiveData<ApiResponse<User>> call = ApiUtil.successCall(user);
when(githubService.getUser("foo")).thenReturn(call);
Observer<Resource<User>> observer = mock(Observer.class);
repo.loadUser("foo").observeForever(observer);
verify(githubService, never()).getUser("foo");
MutableLiveData<User> updatedDbData = new MutableLiveData<>();
when(userDao.findByLogin("foo")).thenReturn(updatedDbData);
dbData.setValue(null);
verify(githubService).getUser("foo");
}
開發者ID:hbmartin,項目名稱:firebase-chat-android-architecture-components,代碼行數:17,代碼來源:UserRepositoryTest.java
示例4: sendResultToUI
import android.arch.lifecycle.MutableLiveData; //導入依賴的package包/類
@Test
public void sendResultToUI() {
MutableLiveData<Resource<User>> foo = new MutableLiveData<>();
MutableLiveData<Resource<User>> bar = new MutableLiveData<>();
when(userRepository.loadUser("foo")).thenReturn(foo);
when(userRepository.loadUser("bar")).thenReturn(bar);
Observer<Resource<User>> observer = mock(Observer.class);
userViewModel.getUser().observeForever(observer);
userViewModel.setLogin("foo");
verify(observer, never()).onChanged(any(Resource.class));
User fooUser = TestUtil.createUser("foo");
Resource<User> fooValue = Resource.success(fooUser);
foo.setValue(fooValue);
verify(observer).onChanged(fooValue);
reset(observer);
User barUser = TestUtil.createUser("bar");
Resource<User> barValue = Resource.success(barUser);
bar.setValue(barValue);
userViewModel.setLogin("bar");
verify(observer).onChanged(barValue);
}
開發者ID:hbmartin,項目名稱:firebase-chat-android-architecture-components,代碼行數:23,代碼來源:UserViewModelTest.java
示例5: RepoViewModel
import android.arch.lifecycle.MutableLiveData; //導入依賴的package包/類
@Inject
public RepoViewModel(RepoRepository repository) {
this.repoId = new MutableLiveData<>();
repo = Transformations.switchMap(repoId, input -> {
if (input.isEmpty()) {
return AbsentLiveData.create();
}
return repository.loadRepo(input.owner, input.name);
});
contributors = Transformations.switchMap(repoId, input -> {
if (input.isEmpty()) {
return AbsentLiveData.create();
} else {
return repository.loadContributors(input.owner, input.name);
}
});
}
示例6: search_fromDb
import android.arch.lifecycle.MutableLiveData; //導入依賴的package包/類
@Test
public void search_fromDb() {
List<Integer> ids = Arrays.asList(1, 2);
Observer<Resource<List<Repo>>> observer = mock(Observer.class);
MutableLiveData<RepoSearchResult> dbSearchResult = new MutableLiveData<>();
MutableLiveData<List<Repo>> repositories = new MutableLiveData<>();
when(dao.search("foo")).thenReturn(dbSearchResult);
repository.search("foo").observeForever(observer);
verify(observer).onChanged(Resource.loading(null));
verifyNoMoreInteractions(service);
reset(observer);
RepoSearchResult dbResult = new RepoSearchResult("foo", ids, 2, null);
when(dao.loadOrdered(ids)).thenReturn(repositories);
dbSearchResult.postValue(dbResult);
List<Repo> repoList = new ArrayList<>();
repositories.postValue(repoList);
verify(observer).onChanged(Resource.success(repoList));
verifyNoMoreInteractions(service);
}
示例7: swap
import android.arch.lifecycle.MutableLiveData; //導入依賴的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");
}
示例8: setup
import android.arch.lifecycle.MutableLiveData; //導入依賴的package包/類
@Before
public void setup() throws Exception {
// init realm database
mockRealmDatabase = PowerMockito.mock(RealmDatabase.class);
// ============ init user data store ==============
mUser = sampleUser(1L);
// noinspection unchecked
mMockUserLiveData = PowerMockito.mock(MutableLiveData.class);
mockUserDataStore = PowerMockito.mock(UserDataStore.class);
when(mockUserDataStore.getUserLiveData()).thenReturn(mMockUserLiveData);
// ============ init test component ===================
testComponent = DaggerTestComponent.builder()
.dataModule(new DataModule(mockRealmDatabase, mockUserDataStore))
.build();
inject(testComponent);
}
示例9: getMoviesList
import android.arch.lifecycle.MutableLiveData; //導入依賴的package包/類
@MainThread
@NonNull
LiveData<Response<List<Country>>> getMoviesList() {
if (countriesLiveData == null) {
countriesLiveData = new MutableLiveData<>();
countriesRepository.getCountries()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.doOnSubscribe(disposable -> loadingLiveData.setValue(true))
.doAfterTerminate(() -> loadingLiveData.setValue(false))
.subscribe(
countries1 -> countriesLiveData.setValue(Response.success(countries1)),
throwable -> countriesLiveData.setValue(Response.error(throwable))
);
}
return countriesLiveData;
}
示例10: onCreate
import android.arch.lifecycle.MutableLiveData; //導入依賴的package包/類
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_live_data);
tvUsername = findViewById(R.id.tv_username);
username = new MutableLiveData<>();
username.observe(this, new Observer<String>() {
@Override
public void onChanged(@Nullable String s) {
tvUsername.setText(s);
}
});
}
示例11: subscribeTo
import android.arch.lifecycle.MutableLiveData; //導入依賴的package包/類
/**
* Subscribes to the entity states of the given type.
*
* <p>The method returns a {@link LiveData} of map (string ID -> entity state). The ID is
* the {@linkplain io.spine.Identifier#toString(Object) string representation} of
* the corresponding entity ID.
*
* <p>Currently, the element removal is not supported. If a {@link DocumentChange} of type other
* than {@link DocumentChange.Type#ADDED ADDED} or {@link DocumentChange.Type#MODIFIED MODIFIED}
* is encountered, an {@link UnsupportedOperationException} is thrown.
*
* @param targetType the class of the entity to subscribe to
* @param <T> the type of the entity to subscribe to
* @return an instance of {@link LiveData} for the observers to subscribe to
*/
public <T extends Message> LiveData<Map<String, T>> subscribeTo(Class<T> targetType) {
checkNotNull(targetType);
final CollectionReference targetCollection = collectionFor(targetType);
final MutableLiveData<Map<String, T>> result = new MutableLiveData<>();
targetCollection.addSnapshotListener((documentSnapshots, error) -> {
if (error != null) {
final String errorMsg = format(
"Error encountered while listening for the %s state updates.",
targetType
);
Log.e(TAG, errorMsg, error);
} else {
final Parser<T> parser = getParserFor(targetType);
for (DocumentChange change : documentSnapshots.getDocumentChanges()) {
deliverUpdate(change, result, parser);
}
}
});
return result;
}
示例12: subscribeToSingle
import android.arch.lifecycle.MutableLiveData; //導入依賴的package包/類
/**
* Subscribes to the single entity state of the given type.
*
* <p>If multiple records of the given type are found in Firestore,
* an {@link IllegalStateException} is thrown.
*
* <p>If no records of the given type are found in Firestore, the update is ignored (i.e.
* the resulting {@link LiveData} is not triggered).
*
* <p>Currently, the element removal is not supported. If a {@link DocumentChange} of type other
* than {@link DocumentChange.Type#ADDED ADDED} or {@link DocumentChange.Type#MODIFIED MODIFIED}
* is encountered, an {@link UnsupportedOperationException} is thrown.
*
* @param targetType the class of the entity state to subscribe to
* @param <T> the type of the entity state to subscribe to
* @return a instance of {@link LiveData} for the observers to subscribe to
*/
@SuppressWarnings("UnnecessaryReturnStatement") // OK for a fast exit on invalid data.
public <T extends Message> LiveData<T> subscribeToSingle(Class<T> targetType) {
final MutableLiveData<T> liveData = new MutableLiveData<>();
final LiveData<Map<String, T>> allRecordsData = subscribeTo(targetType);
allRecordsData.observeForever(map -> {
if (map == null || map.isEmpty()) {
return;
} else if (map.size() > 1) {
throw newIllegalStateException("Type %s has multiple instances.", targetType);
} else {
final Map.Entry<?, T> singleEntry = map.entrySet()
.iterator()
.next();
final T singleData = singleEntry.getValue();
liveData.postValue(singleData);
}
});
return liveData;
}
示例13: deliverUpdate
import android.arch.lifecycle.MutableLiveData; //導入依賴的package包/類
/**
* Delivers the entity state update represented by the given {@link DocumentChange} to
* the observers of the given {@link LiveData}.
*
* @param change the Firestore document change
* @param destination the {@link LiveData} publishing the update
* @param parser the {@link Parser} for the target entity state type
* @param <T> the entity state type
*/
private static <T extends Message>
void deliverUpdate(DocumentChange change,
MutableLiveData<Map<String, T>> destination,
Parser<T> parser) {
final DocumentChange.Type type = change.getType();
final Map<String, T> currentData = destination.getValue();
final Map<String, T> newData = currentData == null
? newHashMap()
: newHashMap(currentData);
final DocumentSnapshot doc = change.getDocument();
final String id = parseMessageId(doc);
final T newMessage = parseMessage(doc, parser);
if (type == ADDED || type == MODIFIED) {
newData.put(id, newMessage);
} else {
throw newIllegalArgumentException("Unexpected document change: %s", type.toString());
}
destination.postValue(newData);
}
示例14: handleData
import android.arch.lifecycle.MutableLiveData; //導入依賴的package包/類
private LiveData<List<PostsListBean>> handleData(final int offset) {
final MutableLiveData<List<PostsListBean>> liveData = new MutableLiveData<>();
Disposable subscribe = mRetrofit.create(IApi.class).getPostsList(mSlug, offset)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Consumer<List<PostsListBean>>() {
@Override
public void accept(@io.reactivex.annotations.NonNull List<PostsListBean> list) throws Exception {
mList.addAll(list);
liveData.setValue(mList);
}
}, new ErrorAction() {
@Override
public void doAction() {
liveData.setValue(null);
}
}.action());
mDisposable.add(subscribe);
mIsLoading.setValue(false);
return liveData;
}
示例15: getHotMovie
import android.arch.lifecycle.MutableLiveData; //導入依賴的package包/類
public MutableLiveData<HotMovieBean> getHotMovie() {
final MutableLiveData<HotMovieBean> data = new MutableLiveData<>();
HttpClient.Builder.getDouBanService().getHotMovie().subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<HotMovieBean>() {
@Override
public void onCompleted() {
}
@Override
public void onError(Throwable e) {
data.setValue(null);
}
@Override
public void onNext(HotMovieBean hotMovieBean) {
if (hotMovieBean != null) {
data.setValue(hotMovieBean);
}
}
});
return data;
}