Skip to content

Instantly share code, notes, and snippets.

@FrantisekGazo
Created November 19, 2016 18:36
Show Gist options
  • Save FrantisekGazo/d1a62fcddd0c97453ee6d57efef17916 to your computer and use it in GitHub Desktop.
Save FrantisekGazo/d1a62fcddd0c97453ee6d57efef17916 to your computer and use it in GitHub Desktop.
RxAndroid - EditText watcher
//------------------------------------------------------------------------------
// RXTextView
//------------------------------------------------------------------------------
import android.support.annotation.NonNull;
import android.widget.TextView;
import rx.Observable;
public final class RxTextView {
private RxTextView() {
}
@NonNull
public static Observable<CharSequence> textChanges(@NonNull TextView view) {
return Observable.create(new TextViewTextOnSubscribe(view));
}
}
//------------------------------------------------------------------------------
// TextViewTextOnSubscribe - just package private for RxTextView to use
//------------------------------------------------------------------------------
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.TextView;
import rx.Observable;
import rx.Subscriber;
import rx.android.MainThreadSubscription;
import static rx.android.MainThreadSubscription.verifyMainThread;
final class TextViewTextOnSubscribe
implements Observable.OnSubscribe<CharSequence> {
final TextView view;
TextViewTextOnSubscribe(TextView view) {
this.view = view;
}
@Override
public void call(final Subscriber<? super CharSequence> subscriber) {
verifyMainThread();
final TextWatcher watcher = new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (!subscriber.isUnsubscribed()) {
subscriber.onNext(s);
}
}
@Override
public void afterTextChanged(Editable s) {
}
};
subscriber.add(new MainThreadSubscription() {
@Override
protected void onUnsubscribe() {
view.removeTextChangedListener(watcher);
}
});
view.addTextChangedListener(watcher);
// Emit initial value.
subscriber.onNext(view.getText());
}
}
Subscription editTextSub = RxTextView.textChanges(editText)
.subscribe(new Action1<String>() {
@Override
public void call(String value) {
// do some work with the updated text
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment