当我按需插入或删除可流动更新的行时,请使用下面的过滤器。
val disposable = tasksRepository.getTasks(forceUpdate = false)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.flatMap { listTask ->
Flowable.fromIterable(listTask)
.filter {
when (currentFiltering) {
TasksFilterType.ALL_TASKS -> true
TasksFilterType.ACTIVE_TASKS -> it.isActive
TasksFilterType.COMPLETED_TASKS -> it.isCompleted
}
}.toList().toFlowable()
}
.subscribe(
{
// onNext
nextValue: List<Task> ->
tasks.value = nextValue
},
{
// onError
error ->
tasks.value = emptyList()
}
)
但是,我想知道是否有可能仅通过更改过滤器或添加用户输入的查询字符串来获得另一种发射,或者我应该写一个Single<List<Task>>
并在用户过滤或输入查询关键字时订阅它吗? / p>
答案 0 :(得分:2)
使用combineLatest()
。当任何源可观察对象发出时,产生的可观察对象也会发出。
示例:
private val currentFilter = BehaviorProcessor.createDefault<TasksFilterType>(TasksFilterType.ALL_TASKS)
private val userQuery = BehaviorProcessor.createDefault<String>("")
val disposable = Flowable
.combineLatest(getTasks(), currentFilter, userQuery) { listTask, filter, query ->
listTask
.filter { // filter tasks by filter
when (filter) {
TasksFilterType.ALL_TASKS -> true
TasksFilterType.ACTIVE_TASKS -> it.isActive
TasksFilterType.COMPLETED_TASKS -> it.isCompleted
}
}
.filter { task -> task.contains(query) } // filter tasks by query
}
.subscribeOn(...)
...