Solution 1 :
Example for observe when text changed with RxBinding library:
private val compositeDisposable = CompositeDisposable()
val disposable = editText.textChanges()
.map(CharSequence::toString)
.observeOn(AndroidSchedulers.mainThread())
.subscribe {
tvResult.text = it
}
compositeDisposable.add(disposable)
And don’t forget callcompositeDisposable.clear()
when activity called onDestroy() or fragment called onDestroyView().
Problem :
I am new to RxJava, to learn few fundamentals I’ve created a small project wherein I am trying to observe my EditText for changes in the entered text and updating a TextView.
Here is the code:
These are the instance variables for my Observable and Observers respectively
private Observable<String> editTextObservable;
private Observer<String> textViewObserver;
I am using RxBinding and am subscribing to the text changes like this:
I am doing this in onCreate()
RxTextView.textChanges(etData).
subscribe(new Action1<CharSequence>() {
@Override
public void call(CharSequence charSequence) {
editTextObservable = Observable.create(new ObservableOnSubscribe<String>() {
@Override
public void subscribe(@NonNull ObservableEmitter<String> emitter) throws Throwable {
Log.d(TAG, "onTextChanged subscribe: " + etData.getText().toString());
emitter.onNext(etData.getText().toString());
}
});
}
});
And I am updating my TextView like this:
textViewObserver = new Observer<String>() {
@Override
public void onSubscribe(@NonNull Disposable d) {
Log.d(TAG, "onSubscribe: ");
}
@Override
public void onNext(@NonNull String value) {
Log.d(TAG, "onNext: ");
tvResult.setText(value);
}
@Override
public void onError(@NonNull Throwable e) {
Log.d(TAG, "onError: ");
}
@Override
public void onComplete() {
Log.d(TAG, "onComplete: ");
}
};
When I run the app it does not gives me any error and I can see in the logs the onTextChanged()
listener being called, but the call never goes to subscribe()
method and I am not able to see any result in the TextView. What am I doing wrong here?
Comments
Comment posted by Hans Wurst
Are you allowed to use an extension library for observing the onTextChange event? There is a wrapper for all kinds of events from ui elements, which will provide an observable.
Comment posted by localhost
@HansWurst you mean RxBinding?
Comment posted by Hans Wurst
Yes, this is the library I mean.
Comment posted by localhost
@HansWurst I tried it with RxBinding but still I am not able to see the results. I have updated the question too