Filter list of objects in RxJava

后端 未结 4 1700
南方客
南方客 2021-02-13 07:00

I am trying to filter the list on the basis of it\'s property. For example, Sensors class has a property isActive and I want to get all the objects with isAct

4条回答
  •  不知归路
    2021-02-13 07:23

    This code is working for me.

    import io.reactivex.Observable
    import io.reactivex.android.schedulers.AndroidSchedulers
    import io.reactivex.disposables.Disposable
    import io.reactivex.observers.DisposableSingleObserver
    import io.reactivex.schedulers.Schedulers
    import java.util.*
    import javax.inject.Inject
    import kotlin.collections.ArrayList
    
        class MainPresenter {
        ....
    
        var disposable: Disposable? = null
        fun filterArticlesList(text: String?) {
                if (text == null || text.isEmpty()) {
                    LogDebug.d("filterArticlesList", "cleared text")
                    staticArticlesListFiltered = staticArticlesList
                    getView()?.onFilterListSuccess(staticArticlesListFiltered)
                } else {
                    val locale = Locale.getDefault()
                    val textLower = text.toLowerCase(locale)
                    disposable?.dispose()
                    disposable = (Observable.fromIterable(staticArticlesList)
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .filter { article -> article.title.toLowerCase(locale).contains(textLower) }
                        .toList()
                        .subscribeWith(FilterObserver(this@MainPresenter)))
                }
            }
    
        }
        class FilterObserver(private val presenter: MainPresenter) :
            DisposableSingleObserver>() {
            override fun onSuccess(t: List
    ) { LogDebug.d("FilterObserver", "onSuccess") } override fun onError(e: Throwable) { LogDebug.e("FilterObserver", "onError", e) } }

提交回复
热议问题