RxJava:调用包含观察者的函数时无法在后台线程上调用观察
RxJava : Cannot invoke observe on a background thread when calling function that contains observer
我在我创建的 SearchView
中实现了 RxJava/RxBinding。这是代码
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}")
})
这里是 getSearchUser()
函数的代码
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)
}
}
}
})
}
问题是在 subscribe
块中调用的 getSearchUser
函数导致了这个错误
Exception: Cannot invoke observe on a background thread
我应该怎么做才能解决这个问题?
谢谢
注意:我使用 jakewharton.rxbinding2
作为 SearchView
我加了.map
,把顺序改成了
val queryStream = RxSearchView.queryTextChanges(searchView)
.map { query ->
query.toString()
}
.debounce(400, TimeUnit.MILLISECONDS)
.observeOn(AndroidSchedulers.mainThread())
有效
但我仍然不知道它是如何工作的
我在我创建的 SearchView
中实现了 RxJava/RxBinding。这是代码
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}")
})
这里是 getSearchUser()
函数的代码
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)
}
}
}
})
}
问题是在 subscribe
块中调用的 getSearchUser
函数导致了这个错误
Exception: Cannot invoke observe on a background thread
我应该怎么做才能解决这个问题?
谢谢
注意:我使用 jakewharton.rxbinding2
作为 SearchView
我加了.map
,把顺序改成了
val queryStream = RxSearchView.queryTextChanges(searchView)
.map { query ->
query.toString()
}
.debounce(400, TimeUnit.MILLISECONDS)
.observeOn(AndroidSchedulers.mainThread())
有效
但我仍然不知道它是如何工作的