所以我一直在尝试将我从TextWatcher获得的EditText输入转换为可观察到的流,但是我无法将其转换。
我正在尝试以下
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) {
}
})
我无法确定应该在哪里创建活动,以便可以订阅。
答案 0 :(得分:2)
您可以简单地在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
}
)
答案 1 :(得分:0)