Android Koin+Compose - Is it possible to inject a Composable View

148 views Asked by At

I have a structure today where my Screen Injects widgets, created as Fragments, from other Modules, using named references from Koin. Something like this:

val view2 by inject<Fragment>(named(FRAGMENT_VIEW_2)) {
    parametersOf(
        VALUE11,
        VALUE12
    )
}
val view2 by inject<Fragment>(named(FRAGMENT_VIEW_2)) {
    parametersOf(VALUE22)
}

We are on a mission to replace some of these "Fragment Widgets" for Composable views.

Is there a similar approach to Injecting Fragments for a Composable View?

1

There are 1 answers

0
BenjyTec On

I don't think that is possible because Koin is designed to inject classes/instances, while Composables are functions that are not even encapsulated in a class.

What you could do, however, is to create a Fragment that contains a Composable, and then inject that Fragment the same way as you currently do. There is a dedicated ComposeView view that you can use in your Fragment, as explained in the documentation:

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

Then you inflate this layout in your Fragment like this:

class ExampleFragment : Fragment() {

    private var _binding: FragmentExampleBinding? = null

    // This property is only valid between onCreateView and onDestroyView.
    private val binding get() = _binding!!

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        _binding = FragmentExampleBinding.inflate(inflater, container, false)
        val view = binding.root
        binding.composeView.apply {
            // Dispose of the Composition when the view's LifecycleOwner
            // is destroyed
            setViewCompositionStrategy(ViewCompositionStrategy.DisposeOnViewTreeLifecycleDestroyed)
            setContent {
                // In Compose world
                MaterialTheme {
                    // Place your Composable here
                }
            }
        }
        return view
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }
}