Is there a way to start a composable component in a not composable component

Viewed 27

since Compose is still pretty new I am trying to see better ways to navigate some challenges, for instance I encountered recomposition when trying to listen to Logging In State in my view model. MutableStateFlow<LoggingInState> This lead me to just directly in my ComponentActivity() having my setContent{navigation} and adding in the onCreate() and observerLoggingInState() now my problem is I have this composable AlertDialog that I can't to call in my LoggingInError but off course you can not call a composable outside a composable, and creating a DialogFragment that requires a childFragmentManager yet I have a ComponentActivity() question is how can I navigate this well.

private fun observerLoggingInState(){
 lifecycleScope.launch{
  repeatOnLifecycle(Lifecycle.State.CREATED){ 
  viewmodel.loggingInState.collect{ state -> 
  when(state){
  is LoggingInError -> {
  showAlertDialog
}

}

@Composable
fun AlertDialogSample() {

  AlertDialog()
}
1 Answers

There is a possibility to display compose content into the xml based Android layouts.

You can either add a ComposeView into the XML layout, or create a custom view that extends from the AbstractComposeView

Method 1: Custom View

class ComposeAlertDialogComponent @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyle: Int = 0
) : AbstractComposeView(context, attrs, defStyle) {

    @Composable
    override fun Content() {
        AlertDialog()
    }
}

Method 2: XML Based

  <androidx.compose.ui.platform.ComposeView
                            android:id="@+id/alertDialog"
                            android:layout_width="match_parent"
                            android:layout_height="match_parent" />

Activity

    private fun setupComposeViews() {
        binding.apply {
            alertDialog.apply {
              AlertDialog()
        }
}
Related