我正在做一个Android Compose项目,在这个项目中,我使用Paging3和LazyColumn来显示从网络调用获取的项目列表.Page3的默认行为是在用户滚动时加载基于prefetchDistance
的页面,但在我的例子中,它加载了大约15个页面,每个页面在屏幕启动时包含10条记录.
我试着把prefetchDistace
调到10,但不起作用.
以下是我的代码: ViewModel个
class ShowAllNotificationsViewModel @Inject constructor(private val pagingSource: NotificationPagingSource) :
BaseViewModel() {
private val _uiState =
MutableStateFlow<UIState<BaseResponseModel<NotificationResponseModel?>>>(UIState.StateLoading)
val uiState = _uiState.asStateFlow()
private val _isRefreshing = MutableStateFlow(false)
val isRefreshing = _isRefreshing.asStateFlow()
val items: Flow<PagingData<NotificationModel>> = Pager(
config = PagingConfig(
pageSize = 10,
prefetchDistance = 5,
enablePlaceholders = false,
),
pagingSourceFactory = { pagingSource }
)
.flow
.cachedIn(viewModelScope)
fun refreshData() {
pagingSource.invalidate()
}
}
PagingSource:个
class NotificationPagingSource @Inject constructor(val requestNotificationsUseCase: GetNotificationsUseCase) :
PagingSource<String, NotificationModel>() {
override suspend fun load(params: LoadParams<String>): LoadResult<String, NotificationModel> {
Timber.e(IllegalStateException())
Timber.d("load params = $params")
val responseModel = requestNotificationsUseCase(params.key)
val result = responseModel?.getAsResult();
result?.let {
return@load when (result) {
is Result.Error<*>,
Result.Loading,
is Result.SessionTimeoutError<*> -> {
LoadResult.Error(
SessionTimeoutException()
)
}
is Result.Success -> {
LoadResult.Page(
result.value.data?.notifications ?: listOf(),
prevKey = null,
nextKey = result.value.data?.lastId,
)
}
}
}
return LoadResult.Error(
IllegalStateException()
)
}
override fun getRefreshKey(state: PagingState<String, NotificationModel>): String? {
Timber.d("getRefreshKey = state = $state")
return null
}
}
UI :个
@Composable
fun ShowAllNotificationCompose(items: LazyPagingItems<NotificationModel>) {
Column(
modifier = Modifier
.fillMaxSize()
.background(Color.Black)
) {
Timber.d("ShowAllNotificationCompose : state = ${items.loadState}")
HeaderCompose()
Box(
modifier = Modifier
.weight(1f)
) {
val listState = rememberLazyListState()
LazyColumn(
modifier = Modifier,
state = listState
) {
items(
count = items.itemCount,
key = {
items[it]?.id ?: 0
}
) {
val notificationModel = items[it]
if (notificationModel != null) {
NotificationItem(item = notificationModel)
} else {
NotificationShimmerItem()
}
}
if (items.loadState.append == LoadState.Loading) {
items(2) {
NotificationShimmerItem()
}
}
}
}
}
}
}
有没有办法修改这个设置,以确保分页请求只在达到prefectchDistance
后才被调用.
先谢谢你了.