我正在使用RxPagedListBuilder来获取分页列表。我不知道为什么loadRange()引发的异常不会被捕获到可观察对象的onError()
中。该应用程序刚刚崩溃。知道如何使用RxJava方式处理loadRange()
中的异常吗?
以下是我完整的源代码:
class MinimalPagingActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_paging)
val adapter = DummyPagedListAdapter()
list.adapter = adapter
list.layoutManager = LinearLayoutManager(this)
RxPagedListBuilder(
DummyDataSourceFactory(), 3
).buildObservable().subscribe({
Timber.i(it.toString())
adapter.submitList(it)
}, {
// I want to handle both loadInitial() & loadRange() execeptions here.
Timber.e(it)
})
}
}
class DummyDataSource : PositionalDataSource<String>() {
override fun loadInitial(params: LoadInitialParams, callback: LoadInitialCallback<String>) {
// throw RuntimeException("This exception will go to onError() which is I expected")
callback.onResult(listOf("a", "b", "c"), 0, 6)
}
override fun loadRange(params: LoadRangeParams, callback: LoadRangeCallback<String>) {
throw RuntimeException("This exception will crash the app")
// I want to handle this exception in the returned observable in RxPagedListBuilder. that's, this exception should be passed to onError(), but it didn't.
callback.onResult(listOf("d", "e", "f"))
}
}
class DummyDataSourceFactory : DataSource.Factory<Int, String>() {
override fun create(): DataSource<Int, String> {
return DummyDataSource()
}
}
val diffCallback = object : DiffUtil.ItemCallback<String>() {
override fun areItemsTheSame(oldItem: String, newItem: String): Boolean {
return oldItem == newItem
}
override fun areContentsTheSame(oldItem: String, newItem: String): Boolean {
return oldItem == newItem
}
}
class DummyPagedListAdapter: PagedListAdapter<String, DummyPagedListAdapter.ViewHolder>(diffCallback) {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
return ViewHolder(LayoutInflater.from(parent.context).inflate(R.layout.item_data, parent, false))
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
getItem(position)?.apply {
holder.bind(this)
}
}
class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
fun bind(data: String) {
itemView.data.text = data
}
}
}