Вы можете просто создать расширение в kotlin
, которое возвращает Flowable
из 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 }
}
Тогда используйте это так:
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
}
)