【问题标题】:Android live data transformations on a background thread后台线程上的 Android 实时数据转换
【发布时间】:2021-01-02 13:32:00
【问题描述】:

我看到了this,但我不确定如何实现它,或者如果这是同一个问题,我有一个调解器实时数据,当它的 2 个源实时数据更新或基础数据(房间db) 更新,它似乎工作正常,但如果数据更新很多,它会快速连续刷新很多,我得到一个错误

Cannot run invalidation tracker. Is the db closed?
Cannot access database on the main thread since it may potentially lock the UI for a long period of time

这种情况不会每次都发生,只有当数据库快速连续更新大量更新时,视图模型的问题部分才会出现,

var search: MutableLiveData<String> = getSearchState()
val filters: MutableLiveData<MutableSet<String>> = getCurrentFiltersState()
val searchPokemon: LiveData<PagingData<PokemonWithTypesAndSpeciesForList>>

val isFiltersLayoutExpanded: MutableLiveData<Boolean> = getFiltersLayoutExpanded()

init {

    val combinedValues =
        MediatorLiveData<Pair<String?, MutableSet<String>?>?>().apply {
            addSource(search) {
                value = Pair(it, filters.value)
            }
            addSource(filters) {
                value = Pair(search.value, it)
            }
        }

    searchPokemon = Transformations.switchMap(combinedValues) { pair ->
        val search = pair?.first
        val filters = pair?.second
        if (search != null && filters != null) {
            searchAndFilterPokemonPager(search, filters.toList())
        } else null
    }.distinctUntilChanged()
}

@SuppressLint("DefaultLocale")
private fun searchAndFilterPokemonPager(search: String, filters: List<String>): LiveData<PagingData<PokemonWithTypesAndSpeciesForList>> {
    return Pager(
        config = PagingConfig(
            pageSize = 20,
            enablePlaceholders = false,
            maxSize = 60
        )
    ) {
        if (filters.isEmpty()){
            searchPokemonForPaging(search)
        } else {
            searchAndFilterPokemonForPaging(search, filters)
        }
    }.liveData.cachedIn(viewModelScope)
}

@SuppressLint("DefaultLocale")
private fun getAllPokemonForPaging(): PagingSource<Int, PokemonWithTypesAndSpecies> {
    return repository.getAllPokemonWithTypesAndSpeciesForPaging()
}

@SuppressLint("DefaultLocale")
private fun searchPokemonForPaging(search: String): PagingSource<Int, PokemonWithTypesAndSpeciesForList> {
    return repository.searchPokemonWithTypesAndSpeciesForPaging(search)
}

@SuppressLint("DefaultLocale")
private fun searchAndFilterPokemonForPaging(search: String, filters: List<String>): PagingSource<Int, PokemonWithTypesAndSpeciesForList> {
    return repository.searchAndFilterPokemonWithTypesAndSpeciesForPaging(search, filters)
}

错误实际上是从函数 searchPokemonForPaging 抛出的

例如,当应用程序启动时会发生大约 300 次写入,但是如果我通过使所有内容暂停并使用 runBlocking 返回 Pager 来强制调用关闭主线程,它确实可以工作并且我不再收到错误但是它显然会阻塞用户界面,那么有没有办法使 switchmap 异步或使 searchAndFilterPokemonPager 方法异步返回寻呼机?我知道第二个在技术上是可行的(从异步返回),但也许协程有办法解决这个问题
感谢您的帮助

【问题讨论】:

    标签: android android-room android-livedata kotlin-coroutines android-paging


    【解决方案1】:

    根据@EpicPandaForce 的建议,我有这个解决方案

        val combinedValues =
            MediatorLiveData<Pair<String?, MutableSet<String>?>?>().apply {
                addSource(search) {
                    value = Pair(it, filters.value)
                }
                addSource(filters) {
                    value = Pair(search.value, it)
                }
            }
    
        searchPokemon = combinedValues.switchMap {
            liveData {
                val search = it?.first ?: return@liveData
                val filters = it.second ?: return@liveData
                withContext(Dispatchers.IO){
                    emitSource(searchAndFilterPokemonPager(search, filters.toList()))
                }
            }.distinctUntilChanged()
        }
    

    但我仍然收到此错误

    E/ROOM: Cannot run invalidation tracker. Is the db closed?
    java.lang.IllegalStateException: Cannot access database on the main thread since it may potentially lock the UI for a long period of time.
    

    这是在块中的searchPokemonForPaging(search)行中抛出的

        @SuppressLint("DefaultLocale")
        private fun searchAndFilterPokemonPager(search: String, filters: List<String>): LiveData<PagingData<PokemonWithTypesAndSpeciesForList>> {
            return Pager(
                config = PagingConfig(
                    pageSize = 20,
                    enablePlaceholders = false,
                    maxSize = 60
                )
            ) {
                if (filters.isEmpty()){
                    searchPokemonForPaging(search)
                } else {
                    searchAndFilterPokemonForPaging(search, filters)
                }
            }.liveData.cachedIn(viewModelScope)
        }
    

    在实时数据协程构建器内部调用

    @SuppressLint("DefaultLocale")
    private fun searchPokemonForPaging(search: String): PagingSource<Int, PokemonWithTypesAndSpeciesForList> {
        return repository.searchPokemonWithTypesAndSpeciesForPaging(search)
    }
    

    回购方法

    fun searchPokemonWithTypesAndSpeciesForPaging(search: String): PagingSource<Int, PokemonWithTypesAndSpeciesForList> {
        return pokemonDao.searchPokemonWithTypesAndSpeciesForPaging(search)
    }
    

    DAO 方法

    @Transaction
    @Query("SELECT pokemon_id, pokemon_name, pokemon_image_url, pokemon_sprite FROM Pokemon WHERE pokemon_name LIKE :search ORDER BY pokemon_id ASC")
    fun searchPokemonWithTypesAndSpeciesForPaging(search: String): PagingSource<Int, PokemonWithTypesAndSpeciesForList>
    

    【讨论】:

    • 新异常究竟来自哪里?它不应该在combinedValues.switchMap {里面
    • @EpicPandaForce 添加了更多信息,这是同一个例外
    【解决方案2】:

    您可以使用combineTuple (which is available as a library that I wrote for this specific purpose)(可选)简化组合

    之后,您可以使用liveData { 协程构建器将执行移至后台线程

    现在你的代码看起来像

    val search: MutableLiveData<String> = getSearchState()
    val filters: MutableLiveData<Set<String>> = getCurrentFiltersState()
    val searchPokemon: LiveData<PagingData<PokemonWithTypesAndSpeciesForList>>
    
    val isFiltersLayoutExpanded: MutableLiveData<Boolean> = getFiltersLayoutExpanded()
    
    init {
        searchPokemon = combineTuple(search, filters).switchMap { (search, filters) -> 
            liveData {
                val search = search ?: return@liveData
                val filters = filters ?: return@liveData
    
                withContext(Dispatchers.IO) {
                    emit(searchAndFilterPokemonPager(search, filters.toList()))
                }
            }
        }.distinctUntilChanged()
    }
    

    【讨论】:

    • 你的库看起来很棒,我不知道谁否决了这个答案,我试图实现它但没有库但没有任何成功
    • 我试图这样做,但我有一个错误,我将 livedata 放入 livedata searchPokemon = Transformations.switchMap(combinedValues) { pair -> liveData { withContext(Dispatchers.IO) { emit(searchAndFilterPokemonPager (xSearch, xFilters)) } }.distinctUntilChanged() }
    • 好的,我理解我在实时数据中有实时数据的错误,但不确定如何修复它,因为寻呼机必须作为实时数据或流返回,也许我可以加入它而不是包装它
    • 好的,这就是 switchmap 在你的组合元组上所做的,所以我仍然需要 Transformations.switchmap?
    • 我添加了一个答案来显示我所拥有的,但我仍然有错误被抛出
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-30
    • 2016-08-09
    • 1970-01-01
    相关资源
    最近更新 更多