在Edittext上使用setText的RxTextView.textChanges

时间:2018-06-11 12:27:56

标签: java android android-edittext rx-java2 rx-android

RxTextView.textChanges(editText)
                .map(CharSequence::toString)
                .debounce(200, TimeUnit.MILLISECONDS)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(input -> {
                   output = //...do something with input
                   editText.setText(ouput)
                 }));

当我setText(output)进入循环时。要设置文本,我首先需要删除侦听器,然后再次设置侦听器。如何使用 RxJava

执行此操作

2 个答案:

答案 0 :(得分:3)

  

当我setText(output)进入循环时。要设置文本,我首先需要删除侦听器,然后再次设置侦听器。如何使用 RxJava

执行此操作

为了满足要求,我设法扩展了RxBinding源代码,如下所示。

<强> EditableTextViewTextObservable.java

public class EditableTextViewTextObservable extends InitialValueObservable<CharSequence> {
    private final TextView view;

    EditableTextViewTextObservable(TextView view) {
        this.view = view;
    }

    @Override
    protected void subscribeListener(Observer<? super CharSequence> observer) {
        EditableTextViewTextObservable.Listener listener = new EditableTextViewTextObservable.Listener(view, observer);
        observer.onSubscribe(listener);
        view.addTextChangedListener(listener);
    }

    @Override protected CharSequence getInitialValue() {
        return view.getText();
    }

    final static class Listener extends MainThreadDisposable implements TextWatcher {
        private final TextView view;
        private final Observer<? super CharSequence> observer;

        Listener(TextView view, Observer<? super CharSequence> observer) {
            this.view = view;
            this.observer = observer;
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
        }

        @Override
        public void afterTextChanged(Editable s) {
            if (!isDisposed()) {
                view.removeTextChangedListener(this);
                observer.onNext(s);
                view.addTextChangedListener(this);
            }
        }

        @Override
        protected void onDispose() {
            view.removeTextChangedListener(this);
        }
    }
}

<强> EditableRxTextView.java

public final class EditableRxTextView {
    @CheckResult
    @NonNull
    public static InitialValueObservable<CharSequence> textChanges(@NonNull TextView view) {
        return new EditableTextViewTextObservable(view);
    }
}

<强>用法

EditableRxTextView.textChanges(editText)
            .map(CharSequence::toString)
            .debounce(200, TimeUnit.MILLISECONDS)
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(input -> {
               output = //...do something with input
               editText.setText(ouput)
             }));

答案 1 :(得分:0)

我的解决方案是使用editText.getText().replace(...)来设置文本时不触发TextWatcher