Skip to content

Instantly share code, notes, and snippets.

@martyglaubitz
Created October 26, 2015 21:59
Show Gist options
  • Save martyglaubitz/8768e66ea69a260f2731 to your computer and use it in GitHub Desktop.
Save martyglaubitz/8768e66ea69a260f2731 to your computer and use it in GitHub Desktop.
A reusable click listener which emits an object on click
package de.schlankr.utils;
import android.support.annotation.IdRes;
import android.view.View;
import rx.subjects.PublishSubject;
public class SubjectClickListener <V> implements View.OnClickListener {
public static <V> SubjectClickListener<V> get(final PublishSubject<V> publishSubject, final View clickTarget, final View tagTarget, @IdRes final int listenerId) {
//noinspection unchecked
SubjectClickListener<V> result = (SubjectClickListener<V>) tagTarget.getTag(listenerId);
if (result == null) {
clickTarget.setTag(listenerId, result = new SubjectClickListener<>(publishSubject));
clickTarget.setOnClickListener(result);
}
return result;
}
private final PublishSubject<V> _publishSubject;
private V _subjectObject;
public SubjectClickListener(final PublishSubject<V> publishSubject) {
_publishSubject = publishSubject;
}
@Override
public void onClick(final View view) {
_publishSubject.onNext(_subjectObject);
}
public void setSubjectObject(final V subjectObject) {
_subjectObject = subjectObject;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment