I'd like to use the preview together with NavHost....
# compose-desktop
t
I'd like to use the preview together with NavHost. But I get an error:
Method addObserver must be called on the main thread
Any idea how to solve that issue? Running directly main() works.
Copy code
import androidx.compose.desktop.ui.tooling.preview.Preview
...

fun main() = application {
    Window(onCloseRequest = ::exitApplication) {
        SomeNavPreview()
    }
}

@Composable
@Preview
fun SomeNavPreview() {
    val lifecycleOwner = object : LifecycleOwner {
        override val lifecycle: Lifecycle
            get() = LifecycleRegistry(this)
    }

    CompositionLocalProvider(LocalLifecycleOwner provides lifecycleOwner) {
        val navController: NavHostController = rememberNavController()
        NavHost(
            navController = navController,
            startDestination = "start",
        ) {
            composable(route = "start") {
                Text("hello")
            }
        }
    }
}
Used lib:
Copy code
org.jetbrains.androidx.navigation:navigation-compose:2.8.0-alpha10
Issue:
Copy code
Caused by: java.lang.IllegalStateException: Method addObserver must be called on the main thread
	at androidx.lifecycle.LifecycleRegistry.enforceMainThreadIfNeeded(LifecycleRegistry.jvm.kt:302)
	at androidx.lifecycle.LifecycleRegistry.addObserver(LifecycleRegistry.jvm.kt:180)
	at androidx.savedstate.SavedStateRegistryController_jvmKt.platformPerformAttach(SavedStateRegistryController.jvm.kt:24)
	at androidx.savedstate.SavedStateRegistryController.performAttach(SavedStateRegistryController.kt:49)
	at androidx.navigation.NavBackStackEntry.updateState(NavBackStackEntry.jb.kt:146)
	at androidx.navigation.NavBackStackEntry.setMaxLifecycle(NavBackStackEntry.jb.kt:134)
	at androidx.navigation.NavController.updateBackStackLifecycle$navigation_runtime(NavController.jb.kt:811)
	at androidx.navigation.NavController.dispatchOnDestinationChanged(NavController.jb.kt:703)
	at androidx.navigation.NavController.navigate(NavController.jb.kt:1125)
	at androidx.navigation.NavController.onGraphCreated(NavController.jb.kt:934)
	at androidx.navigation.NavController.setGraph(NavController.jb.kt:851)
	at androidx.navigation.NavController.setGraph(NavController.jb.kt:58)
	at androidx.navigation.compose.NavHostKt.NavHost(NavHost.kt:516)
	at androidx.navigation.compose.NavHostKt.NavHost(NavHost.kt:231)
...
👀 1
After some try and error, I could find the solution. I had to remove this dependency in order to make preview working.
Copy code
org.jetbrains.kotlinx:kotlinx-coroutines-swing:1.9.0