Compose 使用 Flow<T>.collectAsState render List<T> LazyColumn progressive

Compose use Flow<T>.collectAsState render List<T> LazyColumn progressive

我有一个文件列表,需要从每个文件中查询数据,然后将 Result 列表渲染到 LazyColumn

但是在所有查询完成之前我不想渲染列表,如下所示:

class Repo {
    private val list = listOf(fileA, fileB)

    fun query(key: String): Flow<List<Result>> 
        = list.asFlow().map{ it.query(key) }.toList()
} 


@Composable
fun ListView(repo: Repo){
    val res = repo.query("xxx").collectAsState(xxx)

    LazyColumn{
        items(res){ xxx }
    }
}

如何从 Flow.collectAsState progressive

渲染 LazyColumn

class Repo {
    private val list = listOf(fileA, fileB)

    fun query(key: String): Flow<Result> 
        = list.asFlow().map{ it.query(key) }
} 

@Composable
fun ListView(repo: Repo){
    val res = repo.query("xxx").collectAsState(xxx)

    LazyColumn{
        // ???
        items(res){ xxx }
    }
}

刚发现 derivedStateOf 功能非常适合这个。


class Repo {
    private val list = listOf(fileA,fileB)

    fun query(key: String): Flow<Result> = list.asFlow().map{xxx}
} 

@Composable
fun ListView(repo: Repo){
    val flow = repo.query("xxx").collectAsState(xxx)

    val update by remember {
        val data = mutableListOf<Result>()

        derivedStateOf {
            flow?.run(data::add)
            data
        }
    }

    LazyColumn {
        items(update) { data: Result ->
            xxxx
        }
    }

}