Hi everyone, I am working on an app that gets data...
# android
a
Hi everyone, I am working on an app that gets data from an API every 10 seconds and then updates the UI accordingly. I currently have a while loop with a 10s delay that works infinitely.
Copy code
override suspend fun getBusStopModel(): Flow<Resource<SmartBusStop>> {
    return flow {
        while(currentCoroutineContext().isActive){
            try{
                val data = api.getBusService(STOPID).toSmartBusStop()
                emit(Resource.Success<SmartBusStop>(data))
            } catch (e: HttpException){
                emit(Resource.Error(e.localizedMessage ?: "An unexpected error occurred"))
            } catch (e: IOException){
                emit(Resource.Error("Couldn't reach server. Check your internet connection"))
            } catch (e: Exception){
                emit(Resource.Error(e.stackTraceToString()))
            }
            delay(10000)
        }
    }
}
This is called and collected in the view model. I want to ask, is there any better way to achieve a periodic API call. I have looked into work manager a little bit
r
💯 4
Second you should collect from viewLifecycleOwner scope so it'll be cancelled when the View isn't active https://developer.android.com/topic/libraries/architecture/coroutines
👍 1
WorkManager is probably not what you want if you're fetching data constantly for UI
a
Thanks for the corrections Robert, I have made the necessary changes. About the periodic API calls, am I in the right direction, or is there anything else I should look into?
r
Nope, while + delay is pretty standard pattern and will work fine as long as you're not too sensitive about things happening exactly every 10 seconds
a
We are not too sensitive about it, thanks again
l
you can also use the
fixedPeriodTicker
or
fixedDelayTicker
functions
m
You could use a WorkManager combined with a SharedFlow / StateFlow
Whenever a View is active its ViewModel can subscribe to the SharedFlow
Keep the SharedFlow as singleton and have the WorkManager emit data every 10 sec
d
@Martin Nowosad but this only introduces more unnecessary complexity because there is still need for the while - true - delay in the worker + singleton + this might still work indefinitely in the background and if it's only needed for the UI, then then collecting the flow using the viewLifecycleOwner of the fragment would be the cleanest way because this also stops the flow when the fragment is not on screen and is quite straightforward