RxJava2-监听EditText变化并查询数据库并更新UI

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
Disposable subscription = RxTextView.textChangeEvents(etSearch)
.debounce(200, TimeUnit.MILLISECONDS)
.observeOn(AndroidSchedulers.mainThread())
.toFlowable(BackpressureStrategy.BUFFER)
.switchMap(new Function<TextViewTextChangeEvent, Publisher<RealmResults<Note>>>() {
@Override
public Publisher<RealmResults<Note>> apply(TextViewTextChangeEvent event) throws Exception {
String etContent = event.getText().toString();
if (etContent.length() > 0) {
mLv.setVisibility(View.VISIBLE);
} else {
mLv.setVisibility(View.GONE);
}
if (etContent.length() > 0) {
mLv.setVisibility(View.VISIBLE);
} else {
mLv.setVisibility(View.GONE);
}
finalMAdapter.setSearchStr(etContent);
if (dirId == MyApplication.DEFAULT_DIR_ID) {
return Realm.getDefaultInstance().where(Note.class)
.contains("title", etContent)
.sort("timeMills", Sort.DESCENDING).findAllAsync().asFlowable();
} else {
return Realm.getDefaultInstance().where(Note.class)
.equalTo("dirId", dirId)
.contains("title", etContent)
.sort("timeMills", Sort.DESCENDING).findAllAsync().asFlowable();
}
}
})
.filter(new Predicate<RealmResults<Note>>() {
@Override
public boolean test(RealmResults<Note> notes) throws Exception {
return notes.isLoaded();
}
})
.subscribe(new Consumer<RealmResults<Note>>() {
@Override
public void accept(RealmResults<Note> notes) throws Exception {
mNotes = notes;
if (notes != null && notes.size() > 0) {
llNoResult.setVisibility(View.GONE);
} else {
llNoResult.setVisibility(View.VISIBLE);
}
finalMAdapter.updateAll(mNotes);
}
}, new Consumer<Throwable>() {
@Override
public void accept(Throwable throwable) throws Exception {
throwable.printStackTrace();
}
});