https://kotlinlang.org logo
a

AmrJyniat

11/16/2021, 6:06 PM
How to call a Composable fun from coroutine while collecting a flow? compiler said you can't use Composable fun from another non Composable fun.
z

Zach Klippenstein (he/him) [MOD]

11/16/2021, 6:07 PM
You can’t. As for why, consider what it would mean for a composable called from a suspend fun to emit?
Probably you need to update some
MutableState
from your coroutine, and then in your composable branch on that state
a

AmrJyniat

11/16/2021, 6:13 PM
I collect actions of the fragment in one non-composable fun, so one action need to call a composable fun. maybe I need to call the collecting fun from composable.
z

Zach Klippenstein (he/him) [MOD]

11/16/2021, 6:14 PM
Composable functions emit nodes like UI. That UI has to have somewhere to go. If you called a composable from a coroutine, the UI it emits would have nowhere to go.
Can you share some code?
a

AmrJyniat

11/16/2021, 6:17 PM
The fun that collect actions from VM is:
Copy code
private fun setObservers() {
    lifecycleScope.launch {
        lifecycle.repeatOnLifecycle(Lifecycle.State.STARTED) {
            viewModel.taskDetailsActions.collect { action ->
                when(action){
                    is TaskDetailsActions.ShowSureDeleteTaskDialog -> {
                       ShowSureDeleteTaskDialog() //trigger composable fun to show AlertDialog
                    }
                }
            }
        }
    }
}
z

Zach Klippenstein (he/him) [MOD]

11/16/2021, 6:19 PM
Right, so you probably want to have something like this:
Copy code
var showSureDeleteTaskDialog by mutableStateOf(false)
  private set

private fun setObservers() {
  …
  is TaskDetailsActions.ShowSureDeleteTaskDialog -> {
    showSureDeleteTaskDialog = true
  }
}
and then in a composable,
Copy code
if (viewModel.showSureDeleteTaskDialog) {
  Dialog { … }
}
a

AmrJyniat

11/17/2021, 2:27 PM
Sorry for late response, this solution fine but the code becomes some boilerplate. I think to trigger the dialog from compose directly instead of submit the action to VM then observer it, right?
z

Zach Klippenstein (he/him) [MOD]

11/17/2021, 5:03 PM
If that works, then sure that's an option, but it's probably a question of clean layering and grouping of responsibilities.
🙏 1