Koin-Dependent Composable Previews in Android Jetpack Compose
A Quick Tip For Making Android Jetpack Compose Previews Work With Koin
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()…