【问题标题】:Waiting for data from job.await() to utilise inside Composable等待来自 job.await() 的数据在 Composable 中使用
【发布时间】:2021-08-21 07:23:54
【问题描述】:

我正在遍历一个循环以在可组合内呈现 UI。 在每次迭代下,我想对子列表(我想在异步 {} 中执行)执行某种排序和过滤,并使用该子列表来呈现 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)
        }
      }
    }
  }

【问题讨论】:

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


    【解决方案1】:

    你可以试试这个

    @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)
                }
            }
        }
    }
    

    【讨论】:

    • LaunchedEffect 是否在后台执行?而不是在主线程上?
    • LaunchedEffect 在后台执行,但仍在主线程上。实际上,它使用协程
    • 我想在后台执行一些任务,然后一旦完成,想切换到主线程来执行可组合功能。这可能吗?
    • 做一些计算任务你可以用协程,但如果你真的想在单独的线程中做任务,你可以使用async(Dispatchers.XXX) { you actions}
    猜你喜欢
    • 2022-10-04
    • 2020-05-08
    • 1970-01-01
    • 2018-01-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-24
    相关资源
    最近更新 更多