首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何在Android上实时实现对防火墙的分页工作?

如何在Android上实时实现对防火墙的分页工作?
EN

Stack Overflow用户
提问于 2018-11-26 06:40:45
回答 1查看 762关注 0票数 1

我研究了Doug的解决方案,使用https://github.com/CodingDoug/firebase-jetpack上的安卓体系结构模式分页进行修复。我担心的是,如何使用Android体系结构组件实时工作。我尝试了一个解决方案,描述如下,但也存在一些问题。我试图通过创建一个FirestoreBoundaryCallback来使分页实时工作:-

代码语言:javascript
运行
复制
class FirestoreBoundaryCallback<T>(
    private val baseQuery: Query,
    private val factory: FirestoreQueryDataSource.Factory,
    private val lifecycleOwner: LifecycleOwner): PagedList.BoundaryCallback<QueryItemOrException<T>>() {

private val allLiveData = mutableListOf<FirebaseQueryLiveData>()
private val mutableLoadingState = MutableLiveData<LoadingState>()

val loadingState: LiveData<LoadingState>
    get() = mutableLoadingState

override fun onZeroItemsLoaded() {
    allLiveData.clear()
    mutableLoadingState.value = LoadingState.LOADING_INITIAL
    val query = baseQuery.limit(50)
    val liveData = FirebaseQueryLiveData(query)
    liveData.observe(lifecycleOwner, Observer {
        mergeAllDocs()
        if (mutableLoadingState.value != LoadingState.LOADED) {
            mutableLoadingState.value = LoadingState.LOADED
        }
    })
    allLiveData.add(liveData)
}

override fun onItemAtEndLoaded(itemAtEnd: QueryItemOrException<T>) {
    if (allLiveData.isNotEmpty() && allLiveData.last().value?.data?.documents?.isNotEmpty() == true) {
        val lastDocument = allLiveData.last().value?.data?.documents?.last()
        if (lastDocument != null) {
            val query = baseQuery.startAfter(lastDocument).limit(50)
            val liveData = FirebaseQueryLiveData(query)
            mutableLoadingState.value = LoadingState.LOADING_MORE
            liveData.observe(lifecycleOwner, Observer {
                mergeAllDocs()
                if (mutableLoadingState.value != LoadingState.LOADED) {
                    mutableLoadingState.value = LoadingState.LOADED
                }
            })
            allLiveData.add(liveData)
        }
    }
}

fun mergeAllDocs() {
    val items = mutableListOf<DocumentSnapshot>()
    allLiveData.forEach{
        val docs = it.value?.data?.documents
        if (docs != null) {
            items.addAll(docs)
        }
    }
    factory.setItems(items)
}

override fun onItemAtFrontLoaded(itemAtFront: QueryItemOrException<T>) {
}
}

然后我用以下方式修改了FirestoreQueryDataSource:

代码语言:javascript
运行
复制
class FirestoreQueryDataSource private constructor(
private val documentSnapshots: List<DocumentSnapshot>
) : PageKeyedDataSource<PageKey, DocumentSnapshot>() {

companion object {
    private const val TAG = "FirestoreQueryDataSrc"
}

class Factory(private val query: Query, private val source: Source) : DataSource.Factory<PageKey, DocumentSnapshot>() {
    val sourceLiveData = MutableLiveData<FirestoreQueryDataSource>()
    var documentSnapshots: List<DocumentSnapshot> = mutableListOf()

    fun setItems(items: List<DocumentSnapshot>) {
        sourceLiveData.value?.invalidate()
        documentSnapshots = items
        sourceLiveData.postValue(FirestoreQueryDataSource(documentSnapshots))
    }

    override fun create(): DataSource<PageKey, DocumentSnapshot> {
        val dataSource = FirestoreQueryDataSource(documentSnapshots)
        sourceLiveData.postValue(dataSource)
        return dataSource
    }
}

override fun loadInitial(
        params: LoadInitialParams<PageKey>,
        callback: LoadInitialCallback<PageKey, DocumentSnapshot>) {

    val firstPageDocSnapshots = documentSnapshots.take(params.requestedLoadSize)
    val nextPageKey = getNextPageKey(firstPageDocSnapshots)
    callback.onResult(firstPageDocSnapshots, null, nextPageKey)
}

override fun loadAfter(
        params: LoadParams<PageKey>,
        callback: LoadCallback<PageKey, DocumentSnapshot>) {

    val startAfterIndex = documentSnapshots.indexOf(params.key.startAfterDoc)
    var endIndex = startAfterIndex + params.requestedLoadSize
    if (endIndex > documentSnapshots.size) {
        endIndex = documentSnapshots.size - 1;
    }
    val afterInitialPageDocs = documentSnapshots.subList(startAfterIndex, endIndex)
    val nextPageKey = getNextPageKey(afterInitialPageDocs)
    callback.onResult(afterInitialPageDocs, nextPageKey)
}

override fun loadBefore(
        params: LoadParams<PageKey>,
        callback: LoadCallback<PageKey, DocumentSnapshot>) {
    // The paging here only understands how to append new items to the
    // results, not prepend items from earlier pages.
    callback.onResult(emptyList(), null)
}

private fun getNextPageKey(documents: List<DocumentSnapshot>): PageKey? {
    return if (documents.isNotEmpty()) {
        PageKey(documents.last())
    } else {
        null
    }
}
}

data class PageKey(val startAfterDoc: DocumentSnapshot)

在我的ViewModel中,这是我返回的内容:-

代码语言:javascript
运行
复制
val sourceFactory = FirestoreQueryDataSource.Factory(query, Source.DEFAULT)
        val deserializedDataSourceFactory = sourceFactory.map { snapshot ->
            try {
                val item = QueryItem(Deserializer.deserialize(snapshot, Record::class.java), snapshot.id)
                item.item.id = snapshot.id
                QueryItemOrException(item, null)
            } catch (e: Exception) {
                Log.e(TAG, "Error while deserializing order", e)
                QueryItemOrException<PosOrder>(null, e)
            }
        }
        val boundaryCallback = FirestoreBoundaryCallback<Record>(query, sourceFactory, lifecycleOwner)
        val livePagedList = LivePagedListBuilder(deserializedDataSourceFactory, 30)
                .setFetchExecutor(executors.cpuExecutorService)
                .setBoundaryCallback(boundaryCallback)
                .build()
        return Listing(
                pagedList = livePagedList,
                loadingState = boundaryCallback.loadingState,
                refresh = {
                    sourceFactory.sourceLiveData.value?.invalidate()
                }
        )

性能不佳,我还担心当插入新记录时,第一页将丢失其最后一条记录(因为第一次查询的限制是固定的),第二页将继续在旧的第一页的最后记录之后开始。使用实时更新在Android上分页存储数据的正确方法是什么?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-11-26 08:01:09

分页架构组件的局限性在于不能同时获得实时更新。您必须选择是否需要实时更新或分页。(或者想出完全不使用分页或LiveData的解决方案)。这是因为分页组件的工作方式。它只处理通过将一次性查询分页到实际数据而检索的一组静态数据。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53475903

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档