Koin-Dependent Composable Previews in Android Jetpack Compose

A Quick Tip For Making Android Jetpack Compose Previews Work With Koin

Yanneck Reiß
Tech Takeaways

--

image features a sophisticated and playful composition set against a soft, neutral background. On the left, there’s a vibrantly colored 3D coin, and on the right, a sleek, landscape-oriented smartphone mockup. Between these two elements is a prominent plus icon, symbolizing a connection or addition. Above this arrangement, the phrase “Compose Previews” is written in a stylish, modern font that complements the overall design. The scene balances a clean, modern aesthetic with playful charm.

In this article, you will learn how to set up your Android Jetpack Compose Previews to make them work when they depend on the Koin dependency injection framework.

The Problem

If you use Koin in your Android app development, you will probably be familiar with injecting definitions directly into your composables in the following way:

import androidx.compose.runtime.Composable
import org.koin.compose.koinInject

@Composable
fun MyComposable(
classWeWantToInject: ClassWeWantToInject = koinInject()
) {
// ..
}

As a rule of thumb, the better approach is to create a separate composable and bubble down the values from the injected class as well as function references rather than calling the injected class function directly. Consider the following as an example:


import androidx.compose.runtime.Composable
import org.koin.compose.koinInject

@Composable
fun MyComposable(
classWeWantToInject: ClassWeWantToInject = koinInject()
) {

val name: String by classWeWantToInject.name.collectAsStateWithLifecycle()

MyComposableContent(
modifier = Modifier.fillMaxSize()…

--

--

No responses yet