2

我正在尝试使用Paging 3库来获取Flow<PagingData<Scan>>Room然后检查是否在 recyclerview 中选择了项目,所以我将这个类映射到另一个名为ScanMapper. 为了实现这个映射,每当用户将一个项目标记为选中时,我都会MapMutableStateFlow<Map<Int, State>>. 这里Map查找 anIndex(Int)来获取State,State只是一个enum代表 State 的类UNINITIALISEDUSELECTEDand SELECTED

我将 Map 的值设置为StateFlow<Map<Int,State>>. 问题是,我试图将 与 结合起来Flow<PagingData<Scan>>StateFlow<Map<Int,State>>以便将 也State作为参数传递给ScanMapper类,因为它State取自StateFlow<Map<Int,State>>并且不是原始Scan类的一部分。但是,尽管我使用该功能在项目单击时将项目标记为已选中,但PagingDataAdapter似乎总是会出现这种情况。State UNINITIALISEDmarkSelected(scanId: Int)

请告诉我我在这里缺少什么。

更新

我能够通过使用 a 来实现我想要的功能,Flow<List<Scan>>Paging 3使用带有DiffUtils. 虽然这不是实际的解决方案,因为它消除了pagination using paging 3库,但以下更改允许我执行项目选择:

更新道

@Query("SELECT * FROM scan ORDER BY timeOfStorage DESC")
fun getAllScansList(): Flow<List<Scan>>

ViewModel 中的更新功能

fun getData(context: Context): Flow<List<ScanMapper>> {

    val dao = ScanDatabase.invoke(context).getScanDao()

    return combine(
        dao.getAllScansList(),
        myMap
    ) { scan, stateMap ->
        scan.map {
            it.toScanMapper(stateMap[it.id] ?: State.UNKNOWN)
        }
    }.flatMapLatest {
        flow {
            emit(it)
        }
    }
}

更新的片段代码

mainViewModel.getData(requireContext()).collect {

    adapter.asyncListDiffer.submitList(it as MutableList)
}

原始问题

我的扫描课:

@Entity(tableName = "scan")
@Parcelize
data class Scan (
    @PrimaryKey(autoGenerate = true)
    var id: Int = 0,
    val name: String,
    val recognisedText: String,
    val timeOfStorage: Long,
    val filename: String
): Parcelable {

}

我的 ScanMapper 类:

data class ScanMapper(
    val id: Int,
    val name: String,
    val recognisedText: String,
    val timeOfStorage: Long,
    val filename: String,
    val isSelected: State
)

enum class State{
    UNINITIALISED,
    SELECTED,
    UNSELECTED,
    UNKNOWN
}

Scan 到 ScanMapper 的转换器,反之亦然

fun ScanMapper.mapToScan() =
Scan(
    id = id,
    name = name,
    recognisedText = recognisedText,
    timeOfStorage = timeOfStorage,
    filename = filename
)

fun Scan.toScanMapper(isSelected: State) =
ScanMapper(
    id = id,
    name = name,
    recognisedText = recognisedText,
    timeOfStorage = timeOfStorage,
    filename = filename,
    isSelected = isSelected
)

我在 Dao 中的 PagingSource

@Query("SELECT * FROM scan ORDER BY timeOfStorage DESC")
fun getAllScans(): PagingSource<Int,Scan>

@Query("SELECT id FROM scan")
fun getAllIds(): List<Int>

使用 getScansFlow() 获取流量

fun getScansFlow(context: Context): Flow<PagingData<Scan>> {

    val scanDao = ScanDatabase.invoke(context).getScanDao()

    return Pager(
        config = PagingConfig(
            pageSize = 10,
            maxSize = 30,
            enablePlaceholders = false
        ),
        pagingSourceFactory = { scanDao.getAllScans() }
    ).flow.cachedIn(viewModelScope)

}

为 Room 中存在的 id 初始化 Map

fun initList() =
       viewModelScope.launch {

    var idList: List<Int> = listOf()

    withContext(Dispatchers.IO) {

        val task = async {
            return@async ScanDatabase.invoke(context).getScanDao().getAllIds()
        }
        idList = task.await()
    }

    val map = _myMap.value.toMutableMap()

    for (id in idList) {
        map[id] = State.UNINITIALISED
    }

    _myMap.value = map

}

ViewModel 中获取流并将它们组合起来的函数

    fun getScansSyncFlow(context: Context) {

    viewModelScope.launch {

        combine(
            getScansFlow(context),
            myMap
        ) { scan, stateMap ->
            scan.map {
                it.toScanMapper(stateMap[it.id] ?: State.UNKNOWN)
            }
        }.collect{
           _myFlow.emit(it) 
        }
    }
  }

myFlow是一个StateFlow<PagingData<ScanMapper>?>

这就是我Map在 recyclerview 中更新用户何时选择项目的方式。

fun markSelected(scanId: Int) {

    val map = _myMap.value.toMutableMap()
    map[scanId] = State.SELECTED
    _myMap.value = map
}

然后,myFlowfragment像这样收集这个:

lifecycleScope.launchWhenStarted {

mainViewModel.getScansSyncFlow(requireContext())

mainViewModel.myFlow.collect { data ->

      data?.let {
        
          adapter.submitData(it)
       }
    }
}
4

1 回答 1

4

我看到的直接问题是您使用的是 collect 而不是 collectLatest。由于 submitData 不会返回,您将永远不会收到来自 Flow 的更新。

mainViewModel.myFlow.collectLatest {
  adapter.submitData(it)
}
于 2021-05-13T23:03:20.817 回答