问题描述
我正在尝试使用分页库,从服务器获取列表,并将其与本地数据一起使用,但是我不想为其留出空间(我的应用程序中没有db,并且不想为它添加它), 所以我有调解员,我正在尝试实现PagingSource。该列表应该是可流动的,所以当我删除一个项目时,它将自动更新。
调解人
class EventMediator(
private val id: String,private val remoteDataSource: EventRemote,private val eventLocalData: EvrntsLocal
) : RemoteMediator<Int,EventItem>() {
var hasNextKey = true
override suspend fun load(
loadType: LoadType,state: PagingState<Int,EventItem>
): MediatorResult {
try {
val loadKey = when (loadType) {
LoadType.REFRESH -> STARTING_MEAL_INDEX
LoadType.PREPEND -> return MediatorResult.Success(endOfPaginationReached = true)
LoadType.APPEND -> {
if (!eventLocalData.hasNextKey) {
return MediatorResult.Success(endOfPaginationReached = true)
}
eventLocalData.getNumOfMeals()
}
}
val response = remoteDataSource.getEvents(loadKey)
return if (response is Result.Success) {
hasNextKey = !response.data.lastPage
if (loadType == LoadType.REFRESH) {
eventLocalData.clearMeals()
}
eventLocalData.saveMeals(response.data.items)
MediatorResult.Success(endOfPaginationReached = !hasNextKey)
} else {
MediatorResult.Error(IOException("Failed to get Events"))
}
} catch (e: IOException) {
return MediatorResult.Error(e)
} catch (e: HttpException) {
return MediatorResult.Error(e)
}
}
}
EventSource:
class EventSource(
private val eventLocalData: EvrntsLocal
) : PagingSource<Int,EventItem>() {
override suspend fun load(params: LoadParams<Int>): LoadResult<Int,EventItem> {
val offset = (params.key ?: STARTING_MEAL_INDEX)
return try {
val response = eventLocalData.getMeals()
LoadResult.Page(
data = response,prevKey = if (offset - NUM_OF_EVENTS <= STARTING_MEAL_INDEX) null else offset - NUM_OF_EVENTS,nextKey = if (offset + NUM_OF_EVENTS >= response.size) null else offset + NUM_OF_EVENTS
)
} catch (exception: IOException) {
return LoadResult.Error(exception)
} catch (exception: HttpException) {
return LoadResult.Error(exception)
}
}
}
存储库
fun getEvents(folderId: String): Flow<PagingData<EventItem>> {
return Pager(
config = PagingConfig(50),remoteMediator = EventMediator(folderId,remoteDataSource,localDataSource),pagingSourceFactory = { EventSource(localDataSource) }
) .flow
}
我的本地数据:
class EvrntsLocal @Inject constructor(
){
private val _eventChannel = ConflatedBroadcastChannel<List<EventItem>>(emptyList())
var hasNextKey: Boolean = true
fun observeMeals(): Flow<List<EventItem>> {
return _eventChannel.asFlow()
}
fun getMeals(): List<EventItem> {
return _eventChannel.value
}
fun saveMeals(list: List<EventItem>) {
_eventChannel.offer(_eventChannel.value.plus(list))
}
fun getNumOfMeals(): Int {
return _eventChannel.value.size
}
fun clearMeals() {
_eventChannel.offer(emptyList())
}
}
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)