我正在为我的应用程序使用最新的Paging3库,该库具有显示照片列表的图库屏幕,以及显示照片更多选项和信息的详细信息屏幕。我已将图片库设置为在片段的onCreate
中获取照片列表:
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// display all photos, sorted by latest
viewModel.getAllPhotos()
}
如果成功,则照片将通过submitList
传递到适配器,并且如果用户拉下图库屏幕,则应该触发刷新,因此我已相应地设置了refreshListener
。我在onViewCreated
上执行此操作(请注意,我使用ViewBinding):
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding = FragmentGalleryBinding.bind(view)
viewLifecycleOwner.lifecycle.addObserver(viewModel)
setupGallery()
setupRetryButton()
}
private fun setupGallery() {
// Add a click listener for each list item
adapter = GalleryAdapter{ photo ->
photo.id.let {
findNavController().navigate(GalleryFragmentDirections.detailsAction(it))
}
}
viewModel.uiState?.observe(viewLifecycleOwner, {
binding?.swipeLayout?.isRefreshing = false
adapter.submitData(lifecycle, it)
})
binding?.apply {
// Apply the following settings to our recyclerview
list.adapter = adapter.withLoadStateHeaderAndFooter(
header = RetryAdapter {
adapter.retry()
},
footer = RetryAdapter {
adapter.retry()
}
)
// Add a listener for the current state of paging
adapter.addLoadStateListener { loadState ->
Log.d("GalleryFragment", "LoadState: " + loadState.source.refresh.toString())
// Only show the list if refresh succeeds.
list.isVisible = loadState.source.refresh is LoadState.NotLoading
// do not show SwipeRefreshLayout's progress indicator if LoadState is NotLoading
swipeLayout.isRefreshing = loadState.source.refresh !is LoadState.NotLoading
// Show loading spinner during initial load or refresh.
progressBar.isVisible = loadState.source.refresh is LoadState.Loading && !swipeLayout.isRefreshing
// Show the retry state if initial load or refresh fails.
retryButton.isVisible = loadState.source.refresh is LoadState.Error
val errorState = loadState.source.append as? LoadState.Error
?: loadState.source.prepend as? LoadState.Error
?: loadState.append as? LoadState.Error
?: loadState.prepend as? LoadState.Error
errorState?.let {
swipeLayout.isRefreshing = false
Snackbar.make(requireView(),
"\uD83D\uDE28 Wooops ${it.error}",
Snackbar.LENGTH_LONG).show()
}
}
swipeLayout.apply {
setOnRefreshListener {
isRefreshing = true
adapter.refresh()
}
}
}
在第一次加载时,下拉布局会成功触发刷新。但是,在导航到详细信息屏幕后会出现问题。在详细信息屏幕上,按返回按钮可将用户返回画廊。如果用户拉出布局,则会显示进度指示器,但不会发生adapter.refresh()
。我不知道如何调试它。
作为参考,这是我负责抓取照片的ViewModel
的样子:
class GalleryViewModel(private val getAllPhotosUseCase: GetAllPhotosUseCase): BaseViewModel() {
private val _uiState = MutableLiveData<PagingData<UnsplashPhoto>>()
val uiState: LiveData<PagingData<UnsplashPhoto>>? get() = _uiState
fun getAllPhotos() {
compositeDisposable += getAllPhotosUseCase.getAllPhotos()
.cachedIn(viewModelScope)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribeBy(
onNext = { _uiState.value = it },
onError = {
it.printStackTrace()
}
)
}
}
GetAllPhotosUseCase
将getAllPhotos
调用转发到包含以下内容的Repository
实现:
class UnsplashRepoImpl(private val unsplashApi: UnsplashApi): UnsplashRepo {
override fun getAllPhotos(): Observable<PagingData<UnsplashPhoto>> = Pager(
config = PagingConfig(Const.PAGE_SIZE),
remoteMediator = null,
// Always create a new UnsplashPagingSource object. Failure to do so would result in a
// IllegalStateException when adapter.refresh() is called--
// Exception message states that the same PagingSource was used as the prev request,
// and a new PagingSource is required
pagingSourceFactory = { UnsplashPagingSource(unsplashApi) }
).observable
....
}
我的RxPagingSource
的设置如下:
class UnsplashPagingSource (private val unsplashApi: UnsplashApi)
: RxPagingSource<Int, UnsplashPhoto>(){
override fun loadSingle(params: LoadParams<Int>): Single<LoadResult<Int, UnsplashPhoto>> {
val id = params.key ?: Const.PAGE_NUM
return unsplashApi.getAllPhotos(id, Const.PAGE_SIZE, "latest")
.subscribeOn(Schedulers.io())
.map { response ->
response.map { it.toUnsplashPhoto() }
}
.map<LoadResult<Int, UnsplashPhoto>> { item ->
LoadResult.Page(
data = item,
prevKey = if (id == Const.PAGE_NUM) null else id - 1,
nextKey = if (item.isEmpty()) null else id + 1
)
}
.onErrorReturn { e -> LoadResult.Error(e) }
}
}
有人可以以此指向我正确的方向吗?
编辑:正如Jay Dangar所说,将viewModel.getAllPhotos()
移至onResume
将使对adapter.refresh()
的调用成功触发。但是,我不想每次从详细信息屏幕导航到图库时都获取所有照片。为避免这种情况,我在拉布局时不调用adapter.refresh()
,而是调用viewModel.getAllPhotos()
。
我仍然不明白为什么接受的答案有效,但是我认为adapter.refresh()
仅在创建新的PagingSource
或其他功能时有效。
答案 0 :(得分:1)
将您的引荐逻辑放入onResume()而不是onCreate()中,这是生命周期管理的问题。