android.arch.lifecycle.Observer Java Examples
The following examples show how to use
android.arch.lifecycle.Observer.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: LocalData.java From WanAndroid with GNU General Public License v3.0 | 6 votes |
public List<TreeBean> getAllTreeBeans() { String json = PrefHelper.getString(POST_TREE_JSON); if (TextUtils.isEmpty(json)) { net.get().getPostTree().observeForever(new Observer<Result<List<TreeBean>>>() { @Override public void onChanged(@Nullable Result<List<TreeBean>> listResult) { if (listResult == null || listResult.getErrorCode() != Net.ZERO) { return; } putTreeJsons(listResult.getData()); } }); ToastHelper.info(App.getInstance().getString(R.string.start_init_tree_data)); return null; } return gson.fromJson(json, new TypeToken<List<TreeBean>>() {}.getType()); }
Example #2
Source File: OfflineBotPresenter.java From Tok-Android with GNU General Public License v3.0 | 6 votes |
@Override public void start() { mContactInfo = BotManager.getInstance().getBotContactInfo(BotType.OFFLINE_MSG_BOT.getType()); mOfflineBotView.showBotInfo(mContactInfo); mOfflineBotPk = mContactInfo.getKey().getKey(); mOfflineBotTokId = mContactInfo.getTokId(); State.infoRepo() .getFriendInfoLive(mOfflineBotPk) .observe(mOfflineBotView, new Observer<ContactInfo>() { @Override public void onChanged(ContactInfo contactInfo) { mIsFriend = (contactInfo != null); LogUtil.i(TAG, "observer offline bot is friend:" + mIsFriend); mOfflineBotView.showIsFriend(mIsFriend); } }); }
Example #3
Source File: LiveEventBusTest.java From LiveEventBus with Apache License 2.0 | 6 votes |
@Test public void testBroadcastGoodBeanValue() throws Exception { final String key = "key_test_broadcast_good_bean"; final Wrapper<GoodBean> wrapper = new Wrapper<>(null); rule.getActivity().runOnUiThread(new Runnable() { @Override public void run() { LiveEventBus .get(key, GoodBean.class) .observe(rule.getActivity(), new Observer<GoodBean>() { @Override public void onChanged(@Nullable GoodBean s) { wrapper.setTarget(s); } }); } }); Thread.sleep(500); GoodBean bean = new GoodBean(100, "hello"); LiveEventBus .get(key, GoodBean.class) .broadcast(bean); Thread.sleep(500); Assert.assertEquals(wrapper.getTarget().getIntValue(), 100); Assert.assertEquals(wrapper.getTarget().getStrValue(), "hello"); }
Example #4
Source File: SingleLiveEvent.java From Android-VMLib with Apache License 2.0 | 6 votes |
@MainThread @Override public void observe(@NonNull LifecycleOwner owner, @NonNull final Observer<T> observer) { if (single) { if (hasActiveObservers()) { L.d("Multiple observers registered but only one will be notified of changes."); } // Observe the internal MutableLiveData super.observe(owner, new Observer<T>() { @Override public void onChanged(@Nullable T t) { if (mPending.compareAndSet(true, false)) { observer.onChanged(t); } } }); } else { super.observe(owner, observer); } }
Example #5
Source File: SingleLiveEvent.java From settlers-remake with MIT License | 6 votes |
@MainThread public void observe(LifecycleOwner owner, final Observer<T> observer) { if (hasActiveObservers()) { Log.w(TAG, "Multiple observers registered but only one will be notified of changes."); } // Observe the internal MutableLiveData super.observe(owner, new Observer<T>() { @Override public void onChanged(@Nullable T t) { if (mPending.compareAndSet(true, false)) { observer.onChanged(t); } } }); }
Example #6
Source File: LiveEventBusTest.java From LiveEventBus with Apache License 2.0 | 6 votes |
@Test public void testRemoveObserve() throws Exception { Observable<String> observe = LiveEventBus.get("key_test_remove_observe", String.class); Map map = (Map) LiveEventBusTestHelper.getLiveEventField("observerMap", observe); LiveData liveData = (LiveData) LiveEventBusTestHelper.getLiveEventField("liveData", observe); Observer<String> observer = new Observer<String>() { @Override public void onChanged(@Nullable String s) { } }; observe.observeForever(observer); Thread.sleep(500); Assert.assertEquals(map.size(), 1); Assert.assertTrue(liveData.hasActiveObservers()); Assert.assertTrue(liveData.hasObservers()); observe.removeObserver(observer); Thread.sleep(500); Assert.assertEquals(map.size(), 0); Assert.assertFalse(liveData.hasActiveObservers()); Assert.assertFalse(liveData.hasObservers()); }
Example #7
Source File: EarthquakeMapFragment.java From Wrox-ProfessionalAndroid-4E with Apache License 2.0 | 6 votes |
@Override public void onMapReady(GoogleMap googleMap) { mMap = googleMap; // Retrieve the Earthquake View Model for this Fragment. earthquakeViewModel = ViewModelProviders.of(getActivity()).get(EarthquakeViewModel.class); // Get the data from the View Model, and observe any changes. earthquakeViewModel.getEarthquakes() .observe(this, new Observer<List<Earthquake>>() { @Override public void onChanged(@Nullable List<Earthquake> earthquakes) { // Update the UI with the updated database results. if (earthquakes != null) setEarthquakeMarkers(earthquakes); } }); }
Example #8
Source File: MainActivity.java From DataLoader with Apache License 2.0 | 6 votes |
public void testLoadData2(View view) { DemoParam param = new DemoParam(); param.name = COMMON_PARAMS[0]; param.no = 100; DataSource<DemoResult> dataSource = DataLoader.get(DemoDataSource.class).getData2(param); dataSource.result().observe(this, new Observer<DemoResult>() { @Override public void onChanged(@Nullable DemoResult s) { Toast.makeText(MainActivity.this, s.toString(), Toast.LENGTH_SHORT).show(); } }); dataSource.error().observe(this, new Observer<Throwable>() { @Override public void onChanged(@Nullable Throwable throwable) { Toast.makeText(MainActivity.this, throwable.toString(), Toast.LENGTH_SHORT).show(); } }); }
Example #9
Source File: LiveEventBusTest.java From LiveEventBus with Apache License 2.0 | 6 votes |
@Test public void testSendMsgBeforeAndAfterObserve() throws Exception { final String randomKey = "key_random_" + new Random().nextInt(); rule.getActivity().strResult = "null"; rule.getActivity().runOnUiThread(new Runnable() { @Override public void run() { LiveEventBus.get().with(randomKey, String.class).setValue("msg_set_before"); LiveEventBus.get() .with(randomKey, String.class) .observe(rule.getActivity(), new Observer<String>() { @Override public void onChanged(@Nullable String s) { rule.getActivity().strResult = s; } }); LiveEventBus.get().with(randomKey, String.class).setValue("msg_set_after"); } }); Thread.sleep(500); Assert.assertEquals(rule.getActivity().strResult, "msg_set_after"); }
Example #10
Source File: LiveEventBusTest.java From LiveEventBus with Apache License 2.0 | 6 votes |
@Test public void testPostOrderly() throws Exception { final String key = "test_post_orderly"; final List<Integer> result = new ArrayList<>(); LiveEventBus .get(key, Integer.class) .observe(rule.getActivity(), new Observer<Integer>() { @Override public void onChanged(@Nullable Integer integer) { result.add(integer); } }); for (int i = 0; i < 10; i++) { LiveEventBus .get(key, Integer.class) .postOrderly(i); } Thread.sleep(500); for (int i = 0; i < 10; i++) { Assert.assertEquals(result.get(i).intValue(), i); } }
Example #11
Source File: EarthquakeListFragment.java From Wrox-ProfessionalAndroid-4E with Apache License 2.0 | 6 votes |
@Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); // Retrieve the Earthquake View Model for the parent Activity. earthquakeViewModel = ViewModelProviders.of(getActivity()) .get(EarthquakeViewModel.class); // Get the data from the View Model, and observe any changes. earthquakeViewModel.getEarthquakes() .observe(this, new Observer<List<Earthquake>>() { @Override public void onChanged(@Nullable List<Earthquake> earthquakes) { // When the View Model changes, update the List if (earthquakes != null) setEarthquakes(earthquakes); } }); // Register an OnSharedPreferenceChangeListener SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getContext()); prefs.registerOnSharedPreferenceChangeListener(mPrefListener); }
Example #12
Source File: PostTreeFragment.java From WanAndroid with GNU General Public License v3.0 | 6 votes |
@Override public void onObserveViewModel(@NonNull PostTreeViewModel viewModel) { super.onObserveViewModel(viewModel); binding.setRefreshViewModel(viewModel); viewModel.getObservablePostTree().observeData(this, new DataCallbackImp<List<TreeBean>>(binding.refresh) { @Override public void success(List<TreeBean> bean) { viewModel.items.clear(); viewModel.items.addAll(bean); } }); viewModel.mTagClickEvent.observe(this, new Observer<TreeBean>() { @Override public void onChanged(@Nullable TreeBean treeBean) { // ToastHelper.info(treeBean.getName()); CategoryDetailActivity.launch(getActivity(), treeBean); } }); }
Example #13
Source File: LoginActivity.java From 1Rramp-Android with MIT License | 6 votes |
private void init() { progressDialog = new ProgressDialog(this); dataStore = new DataStore(); getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN); steemConnect = SteemConnectUtils.getSteemConnectInstance(); connectivityViewModel = ViewModelProviders.of(this).get(ConnectivityViewModel.class); connectivityViewModel.getConnectivityState().observeForever(new Observer<Boolean>() { @Override public void onChanged(@Nullable Boolean isConnected) { if (isConnected) { enableSigninButton(); showConnectivityBar(); } else { disableSigninButton(); showConnectivityErrorBar(); } } }); }
Example #14
Source File: NotesListActivity.java From RoomDb-Sample with Apache License 2.0 | 6 votes |
private void updateTaskList() { noteRepository.getTasks().observe(this, new Observer<List<Note>>() { @Override public void onChanged(@Nullable List<Note> notes) { if(notes.size() > 0) { emptyView.setVisibility(View.GONE); recyclerView.setVisibility(View.VISIBLE); if (notesListAdapter == null) { notesListAdapter = new NotesListAdapter(notes); recyclerView.setAdapter(notesListAdapter); } else notesListAdapter.addTasks(notes); } else updateEmptyView(); } }); }
Example #15
Source File: LiveDataTestUtil.java From livedata-call-adapter with Apache License 2.0 | 6 votes |
@SuppressWarnings("unchecked") @Nullable static <T> T getLiveDataValue(final LiveData<T> liveData, final long timeOutInSeconds) throws InterruptedException { final Object[] resultHolder = new Object[1]; final CountDownLatch countDownLatch = new CountDownLatch(1); liveData.observeForever(new Observer<T>() { @Override public void onChanged(@Nullable T t) { resultHolder[0] = t; countDownLatch.countDown(); liveData.removeObserver(this); } }); countDownLatch.await(timeOutInSeconds, TimeUnit.SECONDS); if (resultHolder.length == 0) { throw new AssertionError("Unable to retrieve LiveData result"); } return (T) resultHolder[0]; }
Example #16
Source File: LiveEventBusTest.java From LiveEventBus with Apache License 2.0 | 6 votes |
@Test public void testSendMsgBeforeAndAfterObserve() throws Exception { final String randomKey = "key_random_" + new Random().nextInt(); rule.getActivity().strResult = "null"; rule.getActivity().runOnUiThread(new Runnable() { @Override public void run() { LiveEventBus.get().with(randomKey, String.class).setValue("msg_set_before"); LiveEventBus.get() .with(randomKey, String.class) .observe(rule.getActivity(), new Observer<String>() { @Override public void onChanged(@Nullable String s) { rule.getActivity().strResult = s; } }); LiveEventBus.get().with(randomKey, String.class).setValue("msg_set_after"); } }); Thread.sleep(500); Assert.assertEquals(rule.getActivity().strResult, "msg_set_after"); }
Example #17
Source File: LiveDataTestUtil.java From mvvm-template with GNU General Public License v3.0 | 6 votes |
public static <T> T getValue(LiveData<T> liveData) throws InterruptedException { final Object[] data = new Object[1]; 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]; }
Example #18
Source File: LiveEventBusTest.java From LiveEventBus with Apache License 2.0 | 6 votes |
@Test public void testSendMsgBeforeObserve() throws Exception { final String randomKey = "key_random_" + new Random().nextInt(); rule.getActivity().strResult = "null"; rule.getActivity().runOnUiThread(new Runnable() { @Override public void run() { LiveEventBus.get().with(randomKey, String.class).setValue("msg_set_before"); LiveEventBus.get() .with(randomKey, String.class) .observe(rule.getActivity(), new Observer<String>() { @Override public void onChanged(@Nullable String s) { rule.getActivity().strResult = s; } }); } }); Thread.sleep(500); Assert.assertEquals(rule.getActivity().strResult, "null"); }
Example #19
Source File: PostDelayActivity.java From LiveEventBus with Apache License 2.0 | 6 votes |
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_post_delay); binding = DataBindingUtil.setContentView(this, R.layout.activity_post_delay); binding.setLifecycleOwner(this); binding.setHandler(this); LiveEventBus .get(KEY_TEST_DELAY_LIFE_LONG, String.class) .observe(this, new Observer<String>() { @Override public void onChanged(@Nullable String s) { Toast.makeText(PostDelayActivity.this, "receiveCount: " + receiveCount, Toast.LENGTH_SHORT).show(); receiveCount++; } }); }
Example #20
Source File: LiveEventBusTest.java From LiveEventBus with Apache License 2.0 | 6 votes |
@Test public void testSendWrongTypeMsg() throws Exception { final String key = "key_send_wrong_type"; rule.getActivity().strResult = "null"; rule.getActivity().runOnUiThread(new Runnable() { @Override public void run() { LiveEventBus.get() .with(key, String.class) .observe(rule.getActivity(), new Observer<String>() { @Override public void onChanged(@Nullable String s) { rule.getActivity().strResult = s; } }); LiveEventBus.get().with(key, Integer.class).setValue(10); } }); Thread.sleep(500); Assert.assertEquals(rule.getActivity().strResult, "null"); }
Example #21
Source File: LiveEventBus.java From LiveEventBus with Apache License 2.0 | 6 votes |
@Override public void observe(@NonNull LifecycleOwner owner, @NonNull Observer<T> observer) { SafeCastObserver<T> safeCastObserver = new SafeCastObserver<>(observer); //保存LifecycleOwner的当前状态 Lifecycle lifecycle = owner.getLifecycle(); Lifecycle.State currentState = lifecycle.getCurrentState(); int observerSize = getLifecycleObserverMapSize(lifecycle); boolean needChangeState = currentState.isAtLeast(Lifecycle.State.STARTED); if (needChangeState) { //把LifecycleOwner的状态改为INITIALIZED setLifecycleState(lifecycle, Lifecycle.State.INITIALIZED); //set observerSize to -1,否则super.observe(owner, observer)的时候会无限循环 setLifecycleObserverMapSize(lifecycle, -1); } super.observe(owner, safeCastObserver); if (needChangeState) { //重置LifecycleOwner的状态 setLifecycleState(lifecycle, currentState); //重置observer size,因为又添加了一个observer,所以数量+1 setLifecycleObserverMapSize(lifecycle, observerSize + 1); //把Observer置为active hookObserverActive(safeCastObserver, true); } //更改Observer的version hookObserverVersion(safeCastObserver); }
Example #22
Source File: MainActivity.java From RoomDagger2Demo with Apache License 2.0 | 6 votes |
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); DaggerAppComponent.builder() .appModule(new AppModule(getApplication())) .roomModule(new RoomModule(getApplication())) .build() .inject(this); productRepository.findAll().observe(this, new Observer<List<Product>>() { @Override public void onChanged(@Nullable List<Product> products) { Toast.makeText(MainActivity.this, String.format("Product size: %s", products.size()), Toast.LENGTH_SHORT).show(); } }); }
Example #23
Source File: ProjectCategoryFragment.java From WanAndroid with GNU General Public License v3.0 | 6 votes |
@Override public void onObserveViewModel(@NonNull ProjectCategoryViewModel viewModel) { binding.setRefreshViewModel(viewModel); viewModel.getObservableProjectTree().observeData(this, new DataCallbackImp<List<TreeBean>>(binding.refresh) { @Override public void success(List<TreeBean> bean) { viewModel.items.clear(); viewModel.items.addAll(bean); } }); viewModel.mClickEvent.observe(this, new Observer<TreeBean>() { @Override public void onChanged(@Nullable TreeBean treeBean) { ToastHelper.info(treeBean.getName()); } }); }
Example #24
Source File: LiveEventBus.java From LiveEventBus with Apache License 2.0 | 6 votes |
private void hookObserverVersion(@NonNull Observer<T> observer) { try { //get wrapper's version Object objectWrapper = getObserverWrapper(observer); if (objectWrapper == null) { return; } Class<?> classObserverWrapper = objectWrapper.getClass().getSuperclass(); Field fieldLastVersion = classObserverWrapper.getDeclaredField("mLastVersion"); fieldLastVersion.setAccessible(true); //get livedata's version Field fieldVersion = LiveData.class.getDeclaredField("mVersion"); fieldVersion.setAccessible(true); Object objectVersion = fieldVersion.get(this); //set wrapper's version fieldLastVersion.set(objectWrapper, objectVersion); } catch (Exception e) { e.printStackTrace(); } }
Example #25
Source File: LocalUserDataSource.java From MVVM with MIT License | 6 votes |
@Override public LiveData<Lcee<User>> queryUserByUsername(String username) { final MediatorLiveData<Lcee<User>> data = new MediatorLiveData<>(); data.setValue(Lcee.<User>loading()); data.addSource(userService.queryByUsername(username), new Observer<User>() { @Override public void onChanged(@Nullable User user) { if (null == user) { data.setValue(Lcee.<User>empty()); } else { data.setValue(Lcee.content(user)); } } }); return data; }
Example #26
Source File: LiveEventBusTest.java From LiveEventBus with Apache License 2.0 | 6 votes |
@Test public void testPostNull() throws Exception { final String key = "test_post_null"; final Wrapper<Integer> counter = new Wrapper<>(0); final Wrapper<String> result = new Wrapper<>("aaa"); LiveEventBus .get(key, String.class) .post(null); Thread.sleep(500); LiveEventBus .get(key, String.class) .observeSticky(rule.getActivity(), new Observer<String>() { @Override public void onChanged(@Nullable String s) { counter.setTarget(counter.getTarget() + 1); result.setTarget(s); } }); Thread.sleep(500); Assert.assertEquals(counter.getTarget().intValue(), 1); Assert.assertNull(result.getTarget()); }
Example #27
Source File: LiveEventBusTest.java From LiveEventBus with Apache License 2.0 | 6 votes |
@Test public void testBroadcastLongValue() throws Exception { final String key = "key_test_broadcast_long"; final Wrapper<Long> wrapper = new Wrapper<>(null); rule.getActivity().runOnUiThread(new Runnable() { @Override public void run() { LiveEventBus .get(key, Long.class) .observe(rule.getActivity(), new Observer<Long>() { @Override public void onChanged(@Nullable Long s) { wrapper.setTarget(s); } }); } }); Thread.sleep(500); LiveEventBus .get(key, Long.class) .broadcast(Long.valueOf(100)); Thread.sleep(500); Assert.assertEquals(wrapper.getTarget(), Long.valueOf(100)); }
Example #28
Source File: LocalProjectDataSource.java From MVVM with MIT License | 6 votes |
@Override public LiveData<Lcee<Projects>> queryProjects(int page) { final MediatorLiveData<Lcee<Projects>> data = new MediatorLiveData<>(); data.setValue(Lcee.<Projects>loading()); data.addSource(projectsService.queryProjects(page), new Observer<Projects>() { @Override public void onChanged(@Nullable Projects projects) { if (null == projects) { data.setValue(Lcee.<Projects>empty()); } else { // parse items from json projects.itemsFromJson(); data.setValue(Lcee.content(projects)); } } }); return data; }
Example #29
Source File: MainPageFragment.java From GSoC-Info-Android with GNU General Public License v2.0 | 6 votes |
@Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_about, container, false); RecyclerView recyclerView = view.findViewById(R.id.rv_timeline); recyclerView.setLayoutManager(new LinearLayoutManager(getContext())); MainPageViewModel mainPageViewModel = ViewModelProviders.of(getActivity()).get(MainPageViewModel.class); timelineAdapter = new TimelineAdapter(); recyclerView.setAdapter(timelineAdapter); mainPageViewModel.getMainPageCopy().observe(this, new Observer<MainPage.Copy>() { @Override public void onChanged(@Nullable MainPage.Copy copy) { timelineAdapter.setData(copy); } }); return view; }
Example #30
Source File: LiveEventBusTest.java From LiveEventBus with Apache License 2.0 | 6 votes |
@Test public void testBroadcastFloatValue() throws Exception { final String key = "key_test_broadcast_float"; final Wrapper<Float> wrapper = new Wrapper<>(null); rule.getActivity().runOnUiThread(new Runnable() { @Override public void run() { LiveEventBus .get(key, Float.class) .observe(rule.getActivity(), new Observer<Float>() { @Override public void onChanged(@Nullable Float s) { wrapper.setTarget(s); } }); } }); Thread.sleep(500); LiveEventBus .get(key, Float.class) .broadcast(Float.valueOf(100)); Thread.sleep(500); Assert.assertEquals(wrapper.getTarget(), Float.valueOf(100)); }