Hello :wave: I need to implement auto refresh of A...
# multiplatform
m
Hello 👋 I need to implement auto refresh of API call(s) every 5 and 30 mins. I am doing Kotlin mobile multiplatform with Android and iOS. I don’t want to auto refresh call if there is nobody who will consume data, that sounds like a waste of resources. What ideas do you have to solve something like that?
e
Coroutines. One way is using SharedFlow, you’ll have access to the subscriber count and you can start or stop operations based on that. For example you can run a coroutine that will run a loop that triggers your updates eg
Copy code
myScope.launch {
  sharedFlow.subscriptionCount
    .map { it > 0 }
    .distinctUntilChanged()
    .collect { hasNewSubscribers -> toggleRefreshOnOrOff(hasNewSubscribers) }
}
Copy code
myScope.launch { // coroutine to refresh
  var tick = 0
  while(true) {
    val duration = when(count++ mod 2) {
      0 -> 5.minutes
      1 -> 30.minutes
    }
    delay(duration)
    triggerRefresh()
}
or something like that
s
I am also interested. How does threading work in a situation like this? If you do withContext(Dispatchers.IO) does the ios implementation handle thread switching like native swift?
m
Thanks @efemoney that gave me a good hint for one possible solution Thank you 👍