我是RxJava
的新人,只是尝试实施一些示例来更好地了解最新情况,所以我认为我是EditText
,它是一个Observable并发出{textChangeEvent
1}}使用RxBinding
库:
RxTextView.textChangeEvents(searchbar.getEditText())
.debounce(400, TimeUnit.MILLISECONDS)
.filter(new Func1<TextViewTextChangeEvent, Boolean>() {
@Override
public Boolean call(TextViewTextChangeEvent text) {
return (text.text().length() > 2);
}
})
.subscribeOn(AndroidSchedulers.mainThread())
.observeOn(Schedulers.io());
和Retrofit
api来电,其中来电来自上方的Observable
。
所以我宣布了一个函数:
@Override
public Observable<SearchResponse> executeSearch(Observable<RxTextView> queryText) {
return searchService.getSearch(queryText)
.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread());
}
现在我必须将这两者结合起来,所以当文字发生变化时,会有一个新的Retrofit
电话,但我不知道我怎么能通过&#34; queryText
到服务。
我也尝试过:
Observable<TextViewTextChangeEvent>
searchBarText = RxTextView.textChangeEvents(searchbar.getEditText())
.debounce(400, TimeUnit.MILLISECONDS)
.filter(new Func1<TextViewTextChangeEvent, Boolean>() {
@Override
public Boolean call(TextViewTextChangeEvent text) {
Timber.i("Executes!!! text : %s", text.text().toString());
return (text.text().length() > 2);
}
})
.subscribeOn(AndroidSchedulers.mainThread())
.observeOn(Schedulers.io());
Observable.combineLatest(executeSearchTypeOne(searchBarText), executeSearchTypeTwo(searchBarText),
new Func2<TypeOne, TypeTwo, Object>() {
@Override
public Object call(TypeOne one, TypeTwo two) {
return null;
}
})
.subscribe(new Action1<Object>() {
@Override
public void call(Object o) {
Timber.i("WORKS!!!");
}
});
我希望根据Retrofit
更改同时运行两个EditText
来电,但它们根本不会运行
答案 0 :(得分:2)
我假设searchService.getSearch queryText参数的类型是String,并返回一个Observable of Data。
我会这样写:
RxTextView.textChangeEvents(searchbar.getEditText())
.debounce(400, TimeUnit.MILLISECONDS)
.map(new Func1<TextViewTextChangeEvent, String>() {
@Override
public String call(TextViewTextChangeEvent text) {
return text.text().toString();
}
})
.filter(new Func1<String, Boolean>() {
@Override
public Boolean call(String text) {
return (text.length() > 2);
}
})
.flatMap(new Func1<String, rx.Observable<Data>>() {
@Override
public rx.Observable<Data> call(String text) {
return getSearch(text);
}
})
.subscribeOn(Schedulers.io()) // Or Schedulers.newThread()
.observeOn(AndroidSchedulers.mainThread());
这是一个Observable of Data,从一个Observable of TextViewTextChangeEvent映射到String到带有getSearch的链,一个Observable Data。
对于Kotlin(杀手的初步提议):
RxTextView.textChangeEvents(searchbar.getEditText())
.debounce(400, TimeUnit.MILLISECONDS) // Better store the value in a constant like Constant.DEBOUNCE_SEARCH_REQUEST_TIMEOUT
.map { it.text().toString() }
.filter { it.length > 2 }
.flatMap { getSearch(it) } // Or .flatMap(this::getSearch)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe { ... }
注意:运行onError()方法后,RxTextView.textChanges不会发出文本更改。参考:https://github.com/JakeWharton/RxBinding/issues/272