Hi, I have a problem with my LaunchedEffect when I...
# compose-wear
n
Hi, I have a problem with my LaunchedEffect when I navigate back to my main screen from the settings screen. Basically, the LaunchedEffect is activated, which is not what I want. Am I doing something wrong? Please see code in thread.
Copy code
val datastore = AppDataStore(context)
    val workManager = WorkManager.getInstance(context)

    val savedRepeatInterval by datastore.readRepeatInterval.collectAsState(initial = 0L)

    LaunchedEffect(key1 = savedRepeatInterval) {
        val constraints = Constraints.Builder()
            .setRequiredNetworkType(NetworkType.CONNECTED)
            .build()

        val workRequest = savedRepeatInterval.let {
            PeriodicWorkRequestBuilder<PeriodicWorker>(
                it,
                TimeUnit.MINUTES
            ).setConstraints(constraints)
                .addTag("periodic")
                .build()
        }

        WorkManager.getInstance(context)
            .enqueueUniquePeriodicWork(
                "periodic",
                ExistingPeriodicWorkPolicy.UPDATE,
                workRequest
            )
    }
Also, Is there a ScalingLazyGrid?
y
No
So LaunchedEffect will run when a screen is composed. If you navigate away, your state is saved, but the screen composition released.
If you only have two routes, it should have them both live, so when you start swiping back you can see the home screen. But it's not really guaranteed. And if you navigate to a third routes, the home route will be freed.
That code you have, doesn't look like typical UI code, I'd suggest moving to a viewmodel or even better some data layer level objects. Out of the UI
Also you'll likely get two states since you have initial = 0, why not null and only create on non null
n
Thanks, I will move the code out of the UI. 🙂