I'm implementing a screen in jetpack compose where...
# coroutines
a
I'm implementing a screen in jetpack compose where I'm loading data from a remote database, sync it locally and display the items to the user. The way I'm doing it using by using
onRefresh
with a PullToRefresh LazyColumn. The "problem" is that, I'm dependent on location of the device which I extract by using coroutines (in an overall
coroutineScope.launch { }
block. When first loading the app (cold start), the location is not written in DataStore, therefore it leads to the values being null and Compose finishes composing with those values (despite coroutines having been launched). I know that is the whole idea of coroutines: to not wait for them & block for async programming, though, how can I ensure I get my location data before I finish composing the screen and showing to the user the data? The
onRefresh
coroutine block is executed always when the app is started as
isRefreshing
is always set to true so it's equivalent to a
LaunchedEffect(key1 = true)
.
I really don't want to make the code sequential by removing async capability as this would render network calls be executed on Main thread, whereas I want to move them to IO thread for coroutines.
u
You need to display something imediately. That’s how UI works. You can however display something else, while the location is still loading. A white screen, a spinner, a screen with location-aware things blured out. It’s a UX problem. You won’t make the waiting go away. If you’d block, xou woudl also still show something. probably a white screen. If your location then updates, the screen will recompose (if you have location as state 🙂 )
a
Indeed, I'm displaying that I'm loading the data. However, the coroutine seems to finish with null values when I'm explicitly calling other coroutines in the coroutineScope launch block that should fetch the location. It's coroutine block (coroutineScope) finishing before all other coroutines finished. I see no other explanation for why the values that default to null are not updated by the coroutine ending up with an error.
u
yes. and if your location “state variable” is null, you keep displaying the loading screen.
👍🏻 1
aka, make location a flow
thank you color 1