[英]RxJava - How to stop a running task when new item emitted
I am building searching feature for my Android app with RxJava.我正在使用 RxJava 为我的 Android 应用程序构建搜索功能。 When users type/change query characters in an EditText
, an emitter will emit new query text and I search around my database to get results that match the query.当用户在EditText
键入/更改查询字符时,发射器将发出新的查询文本,我在我的数据库中搜索以获得与查询匹配的结果。
getEditTextObservable()
.subscribeOn(Schedulers.computation())
.debounce(500, TimeUnit.MILLISECONDS)
.filter {
!it.isNullOrEmpty()
}
.map {
//start searching
getResultsInDatabase(it) //this function takes a long time to complete
}.observeOn(AndroidSchedulers.mainThread())
.subscribe{
//render results on screen
}
The method getResultsInDatabase(string:String)
take a long time to complete, when the query text changed, I want to stop method getResultsInDatabase(string:String)
(in case it is running with previously emitted query) to run it again with new query.方法getResultsInDatabase(string:String)
需要很长时间才能完成,当查询文本更改时,我想停止方法getResultsInDatabase(string:String)
(以防它使用先前发出的查询运行)以使用新查询再次运行它. How can I do to achieve that?我该怎么做才能实现这一目标? I would appreciate your helps.我会很感激你的帮助。 Thank you for reading my question.感谢您阅读我的问题。
You need a switchMap
.你需要一个switchMap
。
getEditTextObservable()
.subscribeOn(Schedulers.computation())
.debounce(500, TimeUnit.MILLISECONDS)
.filter { !it.isNullOrEmpty() } //Be careful with this. Should clearing text clear results too?
.switchMap {
Observable.fromCallable { getResultsInDatabase(it) }.subscribeOn(Schedulers.io())
}.observeOn(AndroidSchedulers.mainThread())
.subscribe{
//render results on screen
}
You can use valve
to pause a stream in RxJava .您可以使用valve
来暂停RxJava 中的流。 Based on the value of it, the stream continues to emit or will be kept in a paused state.根据它的值,流继续发射或将保持暂停状态。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.