等待来自 job.await() 的数据在 Composable 内部使用

时间:2021-06-03 07:09:02

标签: async-await kotlin-coroutines android-jetpack android-jetpack-compose

我正在迭代一个循环以在可组合内呈现 UI。 在每次迭代下,我想对子列表(我想在 async {} 中执行)执行某种排序和过滤,并使用该子列表来呈现 UI。

有没有办法等待 async{} 完成然后呈现 UI?

  @Composable
  fun MyTree(data: MutableList<Tree>) {
    LazyColumn {
      itemsIndexed(data) { index, tree ->

        // Wanted to perform this operation inside async and use the result to be passed to composables below
        val stems = tree.stems
          ?.sortedBy { it.age }
          ?.filter { it.living != 0 }

        when (tree.type) {
          TYPE1 -> Tree1(stems)
          TYPE2 -> Tree1(stems)
          TYPE3 -> Tree1(stems)
        }
      }
    }
  }

1 个答案:

答案 0 :(得分:0)

你可以试试这个

@Composable
fun MyTree(data: MutableList<Tree>) {

    // maintain the data you want to use in this composable
    // this seem violate the prince "single source truth", but worked
    val stems = remember {
        mutableStateListOf<Tree>()
    }

    LaunchedEffect(key1 = data, block = {
        //  this block will run only if params key1 change
        val stems = tree.stems
            ?.sortedBy { it.age }
            ?.filter { it.living != 0 }
    })


    LazyColumn {

        itemsIndexed(data) { index, tree ->

            // now can use the data stems
            when (tree.type) {
                TYPE1 -> Tree1(stems)
                TYPE2 -> Tree1(stems)
                TYPE3 -> Tree1(stems)
            }
        }
    }
}