androidx.lifecycle.Observer Java Examples

The following examples show how to use androidx.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: FragmentRules.java    From FairEmail with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    DB db = DB.getInstance(getContext());
    db.rule().liveRules(folder).observe(getViewLifecycleOwner(), new Observer<List<TupleRuleEx>>() {
        @Override
        public void onChanged(List<TupleRuleEx> rules) {
            if (rules == null)
                rules = new ArrayList<>();

            adapter.set(rules);

            pbWait.setVisibility(View.GONE);
            grpReady.setVisibility(View.VISIBLE);
        }
    });
}
 
Example #2
Source File: LiveDataTestUtil.java    From mapbox-plugins-android with BSD 2-Clause "Simplified" License 6 votes vote down vote up
/**
 * 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];
}
 
Example #3
Source File: NetworkBoundResource.java    From PopularMovies with MIT License 6 votes vote down vote up
@MainThread
public NetworkBoundResource(AppExecutors appExecutors) {
    mExecutors = appExecutors;
    // Send loading state to UI
    result.setValue(Resource.<ResultType>loading(null));
    final LiveData<ResultType> dbSource = loadFromDb();
    result.addSource(dbSource, new Observer<ResultType>() {
        @Override
        public void onChanged(ResultType data) {
            result.removeSource(dbSource);
            if (shouldFetch(data)) {
                fetchFromNetwork(dbSource);
            } else {
                result.addSource(dbSource, new Observer<ResultType>() {
                    @Override
                    public void onChanged(ResultType newData) {
                        setValue(Resource.success(newData));
                    }
                });
            }
        }
    });
}
 
Example #4
Source File: LiveDataFragment.java    From tv-samples with Apache License 2.0 6 votes vote down vote up
private void subscribeNetworkInfo() {
    NetworkLiveData.sync(getActivity())
            .observe((LifecycleOwner) getActivity(), new Observer<Boolean>() {
                @Override
                public void onChanged(@Nullable Boolean aBoolean) {
                    if (aBoolean) {
                        getActivity().findViewById(R.id.no_internet).setVisibility(View.GONE);

                        // TODO: an appropriate method to re-create the database
                    } else {
                        getActivity().findViewById(R.id.no_internet)
                                .setVisibility(View.VISIBLE);
                    }
                }
            });
}
 
Example #5
Source File: SingleLiveEvent.java    From Deadline with GNU General Public License v3.0 6 votes vote down vote up
@MainThread
@Override
public void observe(@NonNull LifecycleOwner owner, @NonNull final Observer<? super 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 vote down vote up
@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: LoginActivity.java    From UpdogFarmer with GNU General Public License v3.0 6 votes vote down vote up
private void setupViewModel() {
    viewModel = ViewModelProviders.of(this).get(LoginViewModel.class);
    viewModel.init(SteamWebHandler.getInstance());
    viewModel.getTimeDifference().observe(this, new Observer<Integer>() {
        @Override
        public void onChanged(@Nullable Integer value) {
            timeDifference = value;
        }
    });
    viewModel.getTimeout().observe(this, new Observer<Void>() {
        @Override
        public void onChanged(@Nullable Void aVoid) {
            loginInProgress = false;
            loginButton.setEnabled(true);
            progress.setVisibility(View.GONE);
            Snackbar.make(coordinatorLayout, R.string.timeout_error, Snackbar.LENGTH_LONG).show();
        }
    });
}
 
Example #8
Source File: SeekbarFragment.java    From My-MVP with Apache License 2.0 6 votes vote down vote up
private void subscribe() {
    mSeekBar.setOnSeekBarChangeListener(new OnSeekBarChangeAdapterListener(){
        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            super.onProgressChanged(seekBar, progress, fromUser);
            if (fromUser) {
                mSeekbarViewModel.seekbarValue.setValue(progress);
            }
        }
    });

    mSeekbarViewModel.seekbarValue.observe(this, new Observer<Integer>() {
        @Override
        public void onChanged(@Nullable Integer integer) {
            if (integer != null) {
                mSeekBar.setProgress(integer);
            }
        }
    });
}
 
Example #9
Source File: LiveEventBusTest.java    From LiveEventBus with Apache License 2.0 6 votes vote down vote up
@Test
public void testAutoRemoveObserve() throws Exception {
    Observable<String> observe = LiveEventBus.get("key_test_auto_remove_observe", String.class);
    Map map = (Map) LiveEventBusTestHelper.getLiveEventField("observerMap", observe);
    LiveData liveData = (LiveData) LiveEventBusTestHelper.getLiveEventField("liveData", observe);
    observe.observe(rule.getActivity(), new Observer<String>() {
        @Override
        public void onChanged(@Nullable String s) {
        }
    });
    Thread.sleep(500);
    Assert.assertEquals(map.size(), 0);
    Assert.assertTrue(liveData.hasActiveObservers());
    Assert.assertTrue(liveData.hasObservers());
    rule.finishActivity();
    Thread.sleep(1000);
    Assert.assertEquals(map.size(), 0);
    Assert.assertFalse(liveData.hasActiveObservers());
    Assert.assertFalse(liveData.hasObservers());
}
 
Example #10
Source File: LiveEventBusTest.java    From LiveEventBus with Apache License 2.0 6 votes vote down vote up
@Test
public void testBroadcastBundleValue() throws Exception {
    final String key = "key_test_broadcast_bundle";
    final Wrapper<Bundle> wrapper = new Wrapper<>(null);
    rule.getActivity().runOnUiThread(new Runnable() {
        @Override
        public void run() {
            LiveEventBus
                    .get(key, Bundle.class)
                    .observe(rule.getActivity(), new Observer<Bundle>() {
                        @Override
                        public void onChanged(@Nullable Bundle s) {
                            wrapper.setTarget(s);
                        }
                    });
        }
    });
    Thread.sleep(500);
    Bundle bundle = new Bundle();
    bundle.putInt("key_test_int", 100);
    LiveEventBus
            .get(key, Bundle.class)
            .broadcast(bundle);
    Thread.sleep(500);
    Assert.assertEquals(wrapper.getTarget().getInt("key_test_int"), 100);
}
 
Example #11
Source File: LiveEventBusTest.java    From LiveEventBus with Apache License 2.0 6 votes vote down vote up
@Test
public void testBroadcastIntegerValue() throws Exception {
    final String key = "key_test_broadcast_int";
    final Wrapper<Integer> wrapper = new Wrapper<>(null);
    rule.getActivity().runOnUiThread(new Runnable() {
        @Override
        public void run() {
            LiveEventBus
                    .get(key, Integer.class)
                    .observe(rule.getActivity(), new Observer<Integer>() {
                        @Override
                        public void onChanged(@Nullable Integer s) {
                            wrapper.setTarget(s);
                        }
                    });
        }
    });
    Thread.sleep(500);
    LiveEventBus
            .get(key, Integer.class)
            .broadcast(100);
    Thread.sleep(500);
    Assert.assertEquals(wrapper.getTarget().intValue(), 100);
}
 
Example #12
Source File: MainActivity.java    From android-popular-movies-app with Apache License 2.0 6 votes vote down vote up
/**
 * Update the list of MovieEntries from LiveData in MainActivityViewModel
 */
private void observeFavoriteMovies() {
    mMainViewModel.getFavoriteMovies().observe(this, new Observer<List<MovieEntry>>() {
        @Override
        public void onChanged(@Nullable List<MovieEntry> movieEntries) {
            // Set the list of MovieEntries to display favorite movies
            mFavoriteAdapter.setMovies(movieEntries);

            // Restore the scroll position after setting up the adapter with the list of favorite movies
            mMainBinding.rvMovie.getLayoutManager().onRestoreInstanceState(mSavedLayoutState);

            if (movieEntries == null || movieEntries.size() == 0) {
                // When there are no favorite movies, display an empty view
                showEmptyView();
            } else if(!isOnline()) {
                // When offline, make the movie data view visible
                showMovieDataView();
            }
        }
    });
}
 
Example #13
Source File: LiveEventBusTest.java    From LiveEventBus with Apache License 2.0 6 votes vote down vote up
@Test
public void testSendEmptyMsg() throws Exception {
    final String key = "key_test_send_empty_msg";
    final Wrapper<String> result = new Wrapper<>("");
    final Wrapper<Boolean> received = new Wrapper<>(false);
    LiveEventBus

            .get(key, String.class)
            .observe(rule.getActivity(), new Observer<String>() {
                @Override
                public void onChanged(@Nullable String s) {
                    result.setTarget(s);
                    received.setTarget(true);
                }
            });
    Thread.sleep(500);
    LiveEventBus

            .get(key, String.class)
            .post(null);
    Thread.sleep(500);
    Assert.assertNull(result.getTarget());
    Assert.assertTrue(received.getTarget());
}
 
Example #14
Source File: MainActivity.java    From android-popular-movies-app with Apache License 2.0 6 votes vote down vote up
/**
 * Update the list of MovieEntries from LiveData in MainActivityViewModel
 */
private void observeFavoriteMovies() {
    mMainViewModel.getFavoriteMovies().observe(this, new Observer<List<MovieEntry>>() {
        @Override
        public void onChanged(@Nullable List<MovieEntry> movieEntries) {
            // Set the list of MovieEntries to display favorite movies
            mFavoriteAdapter.setMovies(movieEntries);

            // Restore the scroll position after setting up the adapter with the list of favorite movies
            mMainBinding.rvMovie.getLayoutManager().onRestoreInstanceState(mSavedLayoutState);

            if (movieEntries == null || movieEntries.size() == 0) {
                // When there are no favorite movies, display an empty view
                showEmptyView();
            } else if(!isOnline()) {
                // When offline, make the movie data view visible
                showMovieDataView();
            }
        }
    });
}
 
Example #15
Source File: MainActivity.java    From android-popular-movies-app with Apache License 2.0 6 votes vote down vote up
/**
 * Update the MoviePagedList from LiveData in MainActivityViewModel
 */
private void observeMoviePagedList() {
    mMainViewModel.getMoviePagedList().observe(this, new Observer<PagedList<Movie>>() {
        @Override
        public void onChanged(@Nullable PagedList<Movie> pagedList) {
            showMovieDataView();
            if (pagedList != null) {
                mMoviePagedListAdapter.submitList(pagedList);

                // Restore the scroll position after setting up the adapter with the list of movies
                mMainBinding.rvMovie.getLayoutManager().onRestoreInstanceState(mSavedLayoutState);
            }

            // When offline, make the movie data view visible and show a snackbar message
            if (!isOnline()) {
                showMovieDataView();
                showSnackbarOffline();
            }
        }
    });
}
 
Example #16
Source File: HomeFragment.java    From CloudReader with Apache License 2.0 6 votes vote down vote up
public void getWanAndroidBanner() {
    viewModel.getWanAndroidBanner().observe(this, new Observer<WanAndroidBannerBean>() {
        @Override
        public void onChanged(@Nullable WanAndroidBannerBean bean) {
            if (bean != null) {
                headerBinding.rlBanner.setVisibility(View.VISIBLE);
                showBannerView(bean.getData());
            } else {
                headerBinding.rlBanner.setVisibility(View.GONE);
            }
            headerBinding.radioGroup.setVisibility(View.VISIBLE);
            if (headerBinding.rb1.isChecked()) {
                getHomeArticleList();
            } else {
                getHomeProjectList();
            }
        }
    });
}
 
Example #17
Source File: DetailActivity.java    From android-popular-movies-app with Apache License 2.0 6 votes vote down vote up
/**
 * When offline, display runtime, release year, and genre of the movie.
 */
private void loadMovieDetailData() {
    FavViewModelFactory factory = InjectorUtils.provideFavViewModelFactory(
            DetailActivity.this, mMovie.getId());
    mFavViewModel = new ViewModelProvider(this, factory).get(FavViewModel.class);

    mFavViewModel.getMovieEntry().observe(this, new Observer<MovieEntry>() {
        @Override
        public void onChanged(@Nullable MovieEntry movieEntry) {
            if (movieEntry != null) {
                mDetailBinding.tvRuntime.setText(movieEntry.getRuntime());
                mDetailBinding.tvReleaseYear.setText(movieEntry.getReleaseYear());
                mDetailBinding.tvGenre.setText(movieEntry.getGenre());
            }
        }
    });
}
 
Example #18
Source File: LiveEventBusTest.java    From LiveEventBus with Apache License 2.0 6 votes vote down vote up
@Test
public void testBroadcastStringValueForeground() throws Exception {
    final String key = "key_test_broadcast_string_foreground";
    final Wrapper<String> wrapper = new Wrapper<>(null);
    rule.getActivity().runOnUiThread(new Runnable() {
        @Override
        public void run() {
            LiveEventBus
                    .get(key, String.class)
                    .observe(rule.getActivity(), new Observer<String>() {
                        @Override
                        public void onChanged(@Nullable String s) {
                            wrapper.setTarget(s);
                        }
                    });
        }
    });
    Thread.sleep(500);
    LiveEventBus
            .get(key, String.class)
            .broadcast("value_test_broadcast_value", true, false);
    Thread.sleep(500);
    Assert.assertEquals(wrapper.getTarget(), "value_test_broadcast_value");
}
 
Example #19
Source File: FragmentLogs.java    From FairEmail with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    long from = new Date().getTime() - 24 * 3600 * 1000L;

    DB db = DB.getInstance(getContext());
    db.log().liveLogs(from).observe(getViewLifecycleOwner(), new Observer<List<EntityLog>>() {
        @Override
        public void onChanged(List<EntityLog> logs) {
            if (logs == null)
                logs = new ArrayList<>();

            adapter.set(logs);
            if (autoScroll)
                rvLog.scrollToPosition(0);

            pbWait.setVisibility(View.GONE);
            grpReady.setVisibility(View.VISIBLE);
        }
    });
}
 
Example #20
Source File: UsersPreferences.java    From openScale with GNU General Public License v3.0 6 votes vote down vote up
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
                         @Nullable Bundle savedInstanceState) {

   View view = super.onCreateView(inflater, container, savedInstanceState);

    Navigation.findNavController(getActivity(), R.id.nav_host_fragment).getCurrentBackStackEntry().getSavedStateHandle().getLiveData("update", false).observe(getViewLifecycleOwner(), new Observer<Boolean>() {
        @Override
        public void onChanged(Boolean aBoolean) {
            if (aBoolean) {
                updateUserPreferences();
            }
        }
    });

    return view;
}
 
Example #21
Source File: MoodleViewModelTest.java    From ETSMobile-Android2 with Apache License 2.0 6 votes vote down vote up
@Test
public void getAssignmentSubmission() {
    // Prepare LiveData
    MutableLiveData<RemoteResource<MoodleAssignmentSubmission>> liveData = new MutableLiveData<>();
    when(repository.getAssignmentSubmission(anyInt())).thenReturn(liveData);

    // Prepare Observer
    Observer<RemoteResource<MoodleAssignmentSubmission>> observer = mock(Observer.class);
    viewModel.getAssignmentSubmission(anyInt()).observeForever(observer);
    verify(observer, never()).onChanged(any(RemoteResource.class));

    // Set a value and check if onChanged has been called
    RemoteResource<MoodleAssignmentSubmission> remoteRes = RemoteResource.loading(null);
    liveData.setValue(remoteRes);
    verify(observer).onChanged(remoteRes);

    reset(observer);

    // Set another value and check if onChanged has been called again
    remoteRes = RemoteResource.success(new MoodleAssignmentSubmission());
    liveData.setValue(remoteRes);
    verify(observer).onChanged(remoteRes);
}
 
Example #22
Source File: ListsDialog.java    From cathode with Apache License 2.0 6 votes vote down vote up
@Override public void onCreate(@Nullable Bundle inState) {
  super.onCreate(inState);
  Bundle args = getArguments();
  itemType = (ItemType) args.getSerializable(ARG_TYPE);
  itemId = args.getLong(ARG_ID);

  viewModel = ViewModelProviders.of(this).get(ListsDialogViewModel.class);
  viewModel.setItemTypeAndId(itemType, itemId);
  viewModel.getLists().observe(this, new Observer<List<UserList>>() {
    @Override public void onChanged(List<UserList> userLists) {
      setUserLists(userLists);
    }
  });
  viewModel.getListItems().observe(this, new Observer<List<DialogListItem>>() {
    @Override public void onChanged(List<DialogListItem> listItems) {
      setListItems(listItems);
    }
  });
}
 
Example #23
Source File: FragmentAnswers.java    From FairEmail with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    DB db = DB.getInstance(getContext());
    db.answer().liveAnswers().observe(getViewLifecycleOwner(), new Observer<List<EntityAnswer>>() {
        @Override
        public void onChanged(List<EntityAnswer> answers) {
            if (answers == null)
                answers = new ArrayList<>();

            adapter.set(answers);

            pbWait.setVisibility(View.GONE);
            grpReady.setVisibility(View.VISIBLE);
        }
    });
}
 
Example #24
Source File: InformationFragment.java    From android-popular-movies-app with Apache License 2.0 6 votes vote down vote up
/**
 * Every time the user data is updated, the onChanged callback will be invoked and update the UI
 */
private void setupViewModel(Context context, int movieId) {
    InfoViewModelFactory factory = InjectorUtils.provideInfoViewModelFactory(context, movieId);
    mInfoViewModel = new ViewModelProvider(this, factory).get(InfoViewModel.class);

    // Retrieve live data object using the getMovieDetails() method from the ViewModel
    mInfoViewModel.getMovieDetails().observe(getViewLifecycleOwner(), new Observer<MovieDetails>() {
        @Override
        public void onChanged(@Nullable MovieDetails movieDetails) {
            if (movieDetails != null) {
                // Trigger the callback onInformationSelected
                mCallback.onInformationSelected(movieDetails);

                // Display vote count, budget, revenue, status of the movie
                loadMovieDetailInfo(movieDetails);

                // Display cast and crew of the movie
                loadCastCrew(movieDetails);
            }
        }
    });
}
 
Example #25
Source File: LiveEventBusTest.java    From LiveEventBus with Apache License 2.0 6 votes vote down vote up
@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(randomKey, String.class).post("msg_set_before");
            LiveEventBus
                    .get(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 #26
Source File: StickyActivity.java    From LiveEventBus with Apache License 2.0 6 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    binding = DataBindingUtil.setContentView(this, R.layout.activity_sticky_demo);
    binding.setLifecycleOwner(this);
    LiveEventBus
            .get(LiveEventBusDemo.KEY_TEST_STICKY, String.class)
            .observeSticky(this, new Observer<String>() {
                @Override
                public void onChanged(@Nullable String s) {
                    binding.tvSticky1.setText("observeSticky注册的观察者收到消息: " + s);
                }
            });
    LiveEventBus
            .get(LiveEventBusDemo.KEY_TEST_STICKY, String.class)
            .observeStickyForever(observer);
}
 
Example #27
Source File: LiveDataTestUtil.java    From android-room-with-a-view with Apache License 2.0 6 votes vote down vote up
/**
 * 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];
}
 
Example #28
Source File: SingleLiveEvent.java    From UpdogFarmer with GNU General Public License v3.0 6 votes vote down vote up
@MainThread
public void observe(@NonNull LifecycleOwner owner, @NonNull Observer<? super 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 #29
Source File: HomeFragment.java    From guanggoo-android with Apache License 2.0 6 votes vote down vote up
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    inflater.inflate(R.menu.home, menu);

    final MenuItem menuItemNotification = menu.findItem(R.id.action_notifications);
    MenuItemBadge.update(getActivity(), menuItemNotification, new MenuItemBadge.Builder()
            .iconDrawable(ContextCompat.getDrawable(getActivity(), R.drawable.ic_menu_notifications))
            .iconTintColor(Color.WHITE));

    App.getInstance().mGlobal.hasNotifications.observe(this, new Observer<Boolean>() {
        @Override
        public void onChanged(@Nullable Boolean aBoolean) {
            if (aBoolean) {
                MenuItemBadge.getBadgeTextView(menuItemNotification).setHighLightMode(true);
            } else {
                MenuItemBadge.getBadgeTextView(menuItemNotification).clearHighLightMode();
            }
        }
    });

    super.onCreateOptionsMenu(menu, inflater);
}
 
Example #30
Source File: LiveEventBusTest.java    From LiveEventBus with Apache License 2.0 6 votes vote down vote up
@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));
}