Вот моя реализация.
Адаптер состояния загрузки< /strong>
Код: Выделить всё
class LoadStateAdapter (
private val retry: () -> Unit
): LoadStateAdapter() {
override fun onBindViewHolder(holder: LoadStateViewHolder, loadState: LoadState) {
holder.bindTo(loadState)
}
override fun onCreateViewHolder(
parent: ViewGroup,
loadState: LoadState
): LoadStateViewHolder {
return LoadStateViewHolder.create(parent, retry)
}
}
Код: Выделить всё
class LoadStateViewHolder(
view : View,
private val retryCallback: () -> Unit
) : RecyclerView.ViewHolder(view) {
private val progressBar = view.findViewById
(R.id.progress_bar)
private val errorMsg = view.findViewById(R.id.error_msg)
private val btnRetry = view.findViewById(R.id.retry_button)
.also {
it.setOnClickListener { retryCallback() }
}
private var loadState : LoadState? = null
companion object {
fun create(parent: ViewGroup, retryCallback: () -> Unit): LoadStateViewHolder {
val view = LayoutInflater.from(parent.context)
.inflate(R.layout.network_state_item, parent, false)
return LoadStateViewHolder(
view,
retryCallback
)
}
}
fun bindTo(loadState: LoadState) {
this.loadState = loadState
btnRetry.isVisible = loadState !is LoadState.Loading
errorMsg.isVisible = loadState !is LoadState.Loading
progressBar.isVisible = loadState is LoadState.Loading
if (loadState is LoadState.Error){
errorMsg.text = loadState.error.localizedMessage
}
}
}
Код: Выделить всё
override suspend fun load(params: LoadParams): LoadResult {
try {
// Load page 1 if undefined.
val currentPage = params.key ?: 0
val offset = currentPage * 50
val requestParams = hashMapOf()
requestParams.put("limit", 50)
requestParams.put("offset", offset)
val response = repository.getList(requestParams)
val isFinish = response.paging != null && response.paging!!.next == null
return LoadResult.Page(
data = response.data ?: mutableListOf(),
prevKey = null, // Only paging forward.
nextKey = if (isFinish) null else currentPage + 1
)
} catch (e: Exception) {
// Handle errors in this block
return LoadResult.Error(e)
}
}
Код: Выделить всё
val listPagingFlow = Pager(PagingConfig(pageSize = 50)) {
MyPagingSource(repository)
}.flow.cachedIn(viewModelScope)
Код: Выделить всё
val pagingAdapter = MyPagingAdapter()
list.apply {
setHasFixedSize(true)
adapter = pagingAdapter.withLoadStateFooter(
footer = LoadStateAdapter { pagingAdapter.retry() }
)
}
lifecycleScope.launch(Dispatchers.IO) {
viewModel.listPagingFlow.collectLatest { pagingData ->
pagingAdapter.submitData(pagingData)
}
}
Короче; Состояние загрузки работает нормально, но не отображается по первому запросу. Кто-нибудь может помочь?
Текущая версия 3.0.0-alpha04
Подробнее здесь: https://stackoverflow.com/questions/634 ... -not-shown
Мобильная версия