Skip to content

Instantly share code, notes, and snippets.

@medihack
Created June 6, 2019 18:26
Show Gist options
  • Save medihack/af20849fca6bcb93d3d17f1675aabaeb to your computer and use it in GitHub Desktop.
Save medihack/af20849fca6bcb93d3d17f1675aabaeb to your computer and use it in GitHub Desktop.
Make a Android TextView (EditText) observable in RxJava
/**
* Adapted (and translated in Kotlin) from https://gist.github.com/FrantisekGazo/d1a62fcddd0c97453ee6d57efef17916
* Nice usage scenario https://www.novatec-gmbh.de/en/blog/building-android-components/
*/
object RxTextView {
private val textViewObservables = HashMap<TextView, Observable<CharSequence>>()
@JvmStatic
fun textChanges(view: TextView): Observable<CharSequence> {
val observable = textViewObservables[view]
if (observable != null) {
return observable
}
return Observable.create(TextViewTextOnSubscribe(view))
}
}
private class TextViewTextOnSubscribe(val view: TextView): ObservableOnSubscribe<CharSequence> {
override fun subscribe(emitter: ObservableEmitter<CharSequence>) {
MainThreadDisposable.verifyMainThread()
val watcher = object: TextWatcher {
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
}
override fun afterTextChanged(s: Editable?) {
}
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
if (!emitter.isDisposed)
emitter.onNext(s!!)
}
}
view.addTextChangedListener(watcher)
emitter.setCancellable { view.removeTextChangedListener(watcher) }
emitter.onNext(view.text)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment