https://kotlinlang.org logo
#compose
Title
# compose
j

Jan

04/27/2022, 5:52 PM
I have this on the start of my application:
Copy code
LaunchedEffect(Unit) {
            while(true) {
                    delay(7000)
                    try {
                        productMap.fill(ShoppingRepository.getProducts())
                    } catch(e: Exception) {
                        productMap.fill(cache)
                        e.printStackTrace()
                    }
                }
        }
Does this get stopped when the process is not in the foreground or something?
if yes how can I like make this start again after the app gets reopened
o

Oleksandr Balan

04/27/2022, 7:25 PM
I would say this is not really compose related question, as it seems like your use-case is to pull some data each 7 seconds from some API? If yes I would recommend to use
ProcessLifecycleOwner
to observe when application goes to foreground / background. For example you may setup the following in your
Application
class:
Copy code
override fun onCreate() {
    super.onCreate()

    val lifecycle = ProcessLifecycleOwner.get().lifecycle
    lifecycle.addObserver(
        object : DefaultLifecycleObserver {
            
            private var job: Job? = null
            
            override fun onStart(owner: LifecycleOwner) {
                // Application goes to foreground, setup job
                job = lifecycle.coroutineScope.launch {
                    while(isActive) {
                        delay(7000)
                        // Fetch & store
                    }
                }
            }
            
            override fun onStop(owner: LifecycleOwner) {
                // Application goes to background, cancel job
                job?.cancel()
            }
        }
    )
}
o

Orlando Novas Rodriguez

04/29/2022, 2:28 AM
You can use WorkManager; put the request for new data every 15 minutes and save it in the database.
4 Views