Search code examples
androidmultithreadingkotlinrx-java2searchview

RxJava : Cannot invoke observe on a background thread when calling function that contains observer


I implemented RxJava/RxBinding in the SearchView that I created. here is the code

val queryStream = RxSearchView.queryTextChanges(searchView)
    .observeOn(AndroidSchedulers.mainThread())
    .debounce(400, TimeUnit.MILLISECONDS)
 
queryStream.subscribe({
    if (it.isNotEmpty()) {
        Log.e("queryStream", "ini querynya ${it}")
        getSearchUser(it.toString())
    }
}, {
    // Exception
    Log.e("Exception", "${it.message}")
})

and here is the code for getSearchUser() function

private fun getSearchUser(q: String) {
    viewModel.getSearchUser(q).observe(this, { user ->
        if (user != null) {
            when (user) {
                is Resource.Loading -> binding.progressBar.visibility = View.VISIBLE
                is Resource.Success -> {
                    binding.progressBar.visibility = View.GONE
                    adapter.setData(user.data)
                }
                is Resource.Error -> {
                    binding.progressBar.visibility = View.GONE
                    binding.viewError.root.visibility = View.VISIBLE
                    binding.viewError.tvError.text =
                        user.message ?: getString(R.string.something_wrong)
                }
            }
        }
    })
}

the problem is the getSearchUser function that is called inside subscribe block caused this error

Exception: Cannot invoke observe on a background thread

what should I do to fix this problem?

thank you

note: i use jakewharton.rxbinding2 for the SearchView


Solution

  • I added .map and changed the order to

    val queryStream = RxSearchView.queryTextChanges(searchView)
        .map { query ->
            query.toString()
        }
        .debounce(400, TimeUnit.MILLISECONDS)
        .observeOn(AndroidSchedulers.mainThread())
        
    

    and it works

    but I still don't know how it works