2

So i have been trying to convert my EditText input that i get from my TextWatcher to an observable of stream but i cannot convert it.

I am trying the following

etSearch.addTextChangedListener(object: TextWatcher{
        override fun afterTextChanged(p0: Editable?) {
            //I want to create an observable here to send events
               Observable.create(e->e.next(p0));
        }

        override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {

        }

        override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {

        }
    })

I am not able to figure out where i should create my events so that i am able to subscribe to it.

Rajat Beck
  • 1,523
  • 1
  • 14
  • 29

2 Answers2

4

You can simply create an extension in kotlin which returns a Flowable of EditTextFlow

fun EditText.addTextWatcher(): Flowable<EditTextFlow> {
    return Flowable.create<EditTextFlow>({ emitter ->
        addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
                emitter.onNext(EditTextFlow(p0.toString(), EditTextFlow.Type.BEFORE))
            }

            override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
                emitter.onNext(EditTextFlow(p0.toString(), EditTextFlow.Type.ON))
            }

            override fun afterTextChanged(p0: Editable?) {
                emitter.onNext(EditTextFlow(p0.toString(), EditTextFlow.Type.AFTER))
            }
        })
    }, BackpressureStrategy.BUFFER)
}

EditTextFlow

data class EditTextFlow(
        val query: String,
        val type: Type
) {
    enum class Type { BEFORE, AFTER, ON }
}

Then use it like this:

etSearch.addTextWatcher()
                .filter { it.type == EditTextFlow.Type.AFTER }
                .map { it.query }
                .flatMap { /*Make any request or anything*/ }
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeBy(
                        onNext = {
                            // Update UI here
                        },
                        onError = {
                            // Log error
                        }
                )
Prithvi Bhola
  • 3,041
  • 1
  • 16
  • 32
0

Actually, there is a library for this.

You can use it as

RxTextView.textChanges(etSearch)
jujka
  • 1,190
  • 13
  • 18