Skip to content

Instantly share code, notes, and snippets.

@aballano
Last active February 17, 2017 13:28
Show Gist options
  • Save aballano/8af4cd774320c57ced0ec21f8840797e to your computer and use it in GitHub Desktop.
Save aballano/8af4cd774320c57ced0ec21f8840797e to your computer and use it in GitHub Desktop.
Create an observable which emits the action clicked events from a Snackbar.
@RunWith(AndroidJUnit4.class)
public final class RxSnackbarTest {
@Rule public final ActivityTestRule<RxSnackbarTestActivity> activityRule =
new ActivityTestRule<>(RxSnackbarTestActivity.class);
private Snackbar view;
@Before public void setUp() {
RxSnackbarTestActivity activity = activityRule.getActivity();
view = activity.snackbar;
}
@Test public void actionIsClicked() {
String actionText = "Action";
RecordingObserver<Integer> o = new RecordingObserver<>();
RxSnackbar.actionClicked(view, actionText)
.subscribeOn(AndroidSchedulers.mainThread())
.subscribe(o);
o.assertNoMoreEvents();
view.show();
onView(withText(actionText)).perform(click());
o.takeNext();
o.assertNoMoreEvents();
}
@Test public void actionIsClickedButNotSubscribed() {
String actionText = "Action";
RecordingObserver<Integer> o = new RecordingObserver<>();
Subscription subscription = RxSnackbar.actionClicked(view, actionText)
.subscribeOn(AndroidSchedulers.mainThread())
.subscribe(o);
o.assertNoMoreEvents();
view.show();
subscription.unsubscribe();
onView(withText(actionText)).perform(click());
o.assertNoMoreEvents();
}
}
import android.support.design.widget.Snackbar;
import android.view.View;
import android.view.View.OnClickListener;
import rx.Observable;
import rx.Subscriber;
import rx.android.MainThreadSubscription;
final class SnackbarActionOnSubscribe implements Observable.OnSubscribe<Integer> {
final Snackbar view;
final int resId;
final CharSequence text;
public SnackbarActionOnSubscribe(Snackbar view, int resId) {
this.view = view;
this.text = null;
this.resId = resId;
}
public SnackbarActionOnSubscribe(Snackbar view, CharSequence text) {
this.view = view;
this.text = text;
this.resId = -1;
}
@Override
public void call(final Subscriber<? super Integer> subscriber) {
MainThreadSubscription.verifyMainThread();
View.OnClickListener listener = new OnClickListener() {
@Override
public void onClick(View view) {
if (!subscriber.isUnsubscribed()) {
subscriber.onNext(null);
}
}
};
subscriber.add(new MainThreadSubscription() {
@Override
protected void onUnsubscribe() {
view.setCallback(null);
}
});
if (text == null) {
view.setAction(resId, listener);
} else {
view.setAction(text, listener);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment