我有显示项目列表的活动,还有过滤器和搜索选项。我正在使用 android 分页库显示项目。第一次加载项目列表时,当我滚动到底部加载下一组项目时,它的工作正常。但我也想过滤项目并搜索项目。在过滤或搜索项目上,我使现有源无效。如果不使数据源无效,则过滤器和搜索 api 不会触发。我想使用数据源根据我的过滤器和搜索键加载新项目列表。
executor = Executors.newFixedThreadPool(5);
celebrityDataFactory = new CelebrityDataFactory(apicallInterface, mFansismParam);
networkState = Transformations.switchMap(celebrityDataFactory.getCelebrityData(),
dataSource -> dataSource.getNetworkState());
PagedList.Config pagedListConfig =
(new PagedList.Config.Builder())
.setEnablePlaceholders(false)
.setPrefetchDistance(8)
.setInitialLoadSizeHint(10)
.setPageSize(20).build();
if (!mFansismParam.getCategoryId().isEmpty()) {
celebrityDetails = new LivePagedListBuilder(celebrityDataFactory, pagedListConfig)
.setFetchExecutor(executor)
.build();
} else(!mFansismParam.getProfessionId().isEmpty()) {
celebrityDetails = new LivePagedListBuilder(celebrityDataFactory, pagedListConfig)
.setFetchExecutor(executor)
.build();
}
Run Code Online (Sandbox Code Playgroud)
数据工厂创建数据源
@Override
public DataSource create() {
celebrityDataSource = new CelebrityDataSource(apicallInterface, params);
celebrityData.postValue(celebrityDataSource);
return celebrityDataSource;
}
Run Code Online (Sandbox Code Playgroud)
改造 API 调用:
Call<CelebrityList> getCelebrityList(@Query("categoryId") String categoryId,
@Query("professionId") String professionId,
@Query("page") String pageNumber,
@Query("name") String searchKey); …Run Code Online (Sandbox Code Playgroud) android android-search retrofit2 android-paging android-paging-library
我正在尝试在我的应用中使用 Android 新的 Paging 3 库。我正在使用返回对象列表的 Retrofit 从后端 API 获取数据。我需要询问如何在 API 返回空列表时通知 Pager 停止加载更多数据。
提前致谢...
android kotlin android-jetpack android-paging android-paging-library
我正在按照此Codelab使用 github API 和本地数据库构建 paging3 应用程序。虽然前 2 个页面加载良好,但当滚动到底部时尝试加载第 3 个页面时,调解器会遇到循环 - 相同的 PagingState 一遍又一遍地传递给 load() 函数。
只是想知道是否有人知道这里可能的根本原因是什么?
一些实施细节:
RemoteMediator:(prevPage 和 currentPage 来自 github API 的分页响应标头并保存到本地数据库。)
// RepositoryMediator
override suspend fun load(
loadType: LoadType,
state: PagingState<Int, Repository>
): MediatorResult {
return when (loadType) {
LoadType.REFRESH -> {
fireRequestForPage(1, true /*clear DB*/)
return Success(endOfPaginationReached = false)
}
LoadType.APPEND -> {
// !!!!!!! kept getting the same state when APPEND is triggered, resulting in same currentPage and nextPage …Run Code Online (Sandbox Code Playgroud) 我目前正在使用新的 Jetpack compose UI 工具包,我非常喜欢它。我无法弄清楚的一件事是如何stickyHeaders在LazyColumn由分页库填充的a中使用。文档中的非分页示例是:
val grouped = contacts.groupBy { it.firstName[0] }
fun ContactsList(grouped: Map<Char, List<Contact>>) {
LazyColumn {
grouped.forEach { (initial, contactsForInitial) ->
stickyHeader {
CharacterHeader(initial)
}
items(contactsForInitial) { contact ->
ContactListItem(contact)
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
由于我使用的是分页库,groupedBy因此我无法使用它,因此我尝试使用该insertSeparators函数PagingData并像这样自己插入/创建标头(请忽略遗留Date代码,它仅用于测试):
// On my flow
.insertSeparators { before, after ->
when {
before == null -> ListItem.HeaderItem(after?.workout?.time ?: 0)
after == null -> ListItem.HeaderItem(before.workout.time)
(Date(before.workout.time).day != Date(after.workout.time).day) ->
ListItem.HeaderItem(before.workout.time) …Run Code Online (Sandbox Code Playgroud) 我已将页面大小设置为 10,观察者中的页面大小给出了正确的大小,但数据库(ROOM)中的所有项目都已加载到视图持有者中
边界回调onItemAtEndLoaded正在使用数据库中的最后一个项目进行调用。
这是我的配置:
public LiveData<PagedList<Design>> getDesignList(List<String> types, String idCode){
DataSource.Factory<Integer, Design> factory = mRepository.getDesigns(types, idCode);
PagedList.Config pagedListConfig =
(new PagedList.Config.Builder())
.setEnablePlaceholders(false)
.setInitialLoadSizeHint(10)
.setPageSize(10)
.build();
return new LivePagedListBuilder<>(factory, pagedListConfig)
.setBoundaryCallback(**boundCallBack**)
.setFetchExecutor(mRepository.mIoExecutor)
.build();
}
Run Code Online (Sandbox Code Playgroud)
存储库(mRepository.getDesigns):
public DataSource.Factory<Integer, Design> getDesigns(List<String> types, String idCode) {
return designDao.getDesigns(types,idCode);
}
Run Code Online (Sandbox Code Playgroud)
Dao:(获取设计)
@Query("SELECT * FROM Design WHERE design_type IN (:types) AND id=:idCode ORDER BY design_id ASC")
DataSource.Factory<Integer, Design> getDesigns(List<String> types, String idCode);
Run Code Online (Sandbox Code Playgroud)
边界回调(boundCallBack):
public class BoundCall extends …Run Code Online (Sandbox Code Playgroud) android pagedlist android-room android-paging android-paging-library
如何修复IllegalStateException:尝试从pageEventFlow收集两次,这是非法操作。
您是否忘记调用 Flow<PagingData<*>>.cachedIn(coroutineScope) ?
代码:
import androidx.lifecycle.SavedStateHandle
import androidx.lifecycle.ViewModel
import androidx.lifecycle.switchMap
import androidx.lifecycle.viewModelScope
import androidx.paging.cachedIn
import com.kharismarizqii.movieapp.data.MovieRepository
import dagger.hilt.android.lifecycle.HiltViewModel
import javax.inject.Inject
@HiltViewModel
class MovieViewModel @Inject constructor(
private val repository: MovieRepository,
state: SavedStateHandle) : ViewModel(){
companion object{
private const val CURRENT_QUERY = "current_query"
private const val EMPTY_QUERY = ""
}
private val currentQuery = state.getLiveData(CURRENT_QUERY, EMPTY_QUERY)
val movies = currentQuery.switchMap { query ->
if (query.isNotEmpty()){
repository.getSearchMovies(query)
}else{
repository.getNowPlayingMovies().cachedIn(viewModelScope)
}
}
fun searchMovies(query: String){
currentQuery.value = query
}
}
Run Code Online (Sandbox Code Playgroud)
碰撞:
java.lang.IllegalStateException: Attempt …Run Code Online (Sandbox Code Playgroud) android mvvm android-mvvm android-paging-library kotlin-coroutines
从自定义分页实现迁移到Jetpack Paging 3 库后,数据未按预期加载。根据以下内容正确处理第一页:PagingConfigPager
internal fun createProductListPager(pagingSource: ProductListPagingSource): Pager<Int, Product> = Pager(
config = PagingConfig(
pageSize = 10,
prefetchDistance = 2,
),
initialKey = 0,
) { pagingSource }
Run Code Online (Sandbox Code Playgroud)
以下是摘录Adapter:
public class PagingProductCardAdapter(private val viewBinder: CoreViewBinder) :
PagingDataAdapter<Listable, RecyclerView.ViewHolder>(viewBinder.getDiffUtils()) {
public val list: List<Listable>
get() = snapshot().items
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
// ...
}
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
viewBinder.bind(list[position], holder)
}
// ...
}
Run Code Online (Sandbox Code Playgroud)
当滚动到 …
我正在尝试使用 Paging 库、MVVM 和 LiveData 实现一个无限列表。
在我的视图(在我的例子中是我的片段)中,我从 ViewModel 中请求数据并观察变化:
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
viewModel.getItems("someSearchQuery")
viewModel.pagedItems.observe(this, Observer<PagedList<Item>> {
// ItemPagedRecyclerAdapter
// EDIT --> Found this in the official Google example
// Workaround for an issue where RecyclerView incorrectly uses the loading / spinner
// item added to the end of the list as an anchor during initial load.
val layoutManager = (recycler.layoutManager as LinearLayoutManager)
val position = layoutManager.findFirstCompletelyVisibleItemPosition()
if (position != RecyclerView.NO_POSITION) {
recycler.scrollToPosition(position)
}
}) …Run Code Online (Sandbox Code Playgroud) 我有一个 RecyclerView 与 Paging 一起实现,用于从房间数据库加载列表。当尺寸较小时,列表工作正常。当大小达到 50 - 60 左右时,列表仍然可以正常工作,但是当我切换到另一个片段然后返回到列表时,它会阻塞 UI 大约 1.5 - 2 秒,这在用户体验中非常沉闷(参见下面的 GIF) ):
我的代码如下:
DAO
@Query("SELECT * FROM account_table WHERE userID = :userID")
fun getAll(userID: String): DataSource.Factory<Int, Account>
Run Code Online (Sandbox Code Playgroud)
存储库
class AccountRepository private constructor(application: Application) {
private val database =
LockyDatabase.getDatabase(
application
)
private val accountDao = database.accountDao()
companion object {
@Volatile
private var instance: AccountRepository? = null
fun getInstance(application: Application) =
instance ?: synchronized(this) {
instance ?: AccountRepository(application).also { instance = it }
}
}
fun …Run Code Online (Sandbox Code Playgroud) android kotlin android-recyclerview android-paging android-paging-library