https://kotlinlang.org logo
#android-architecture
Title
# android-architecture
m

Mohammed Akram Hussain

03/28/2024, 9:34 AM
What's the best way to make multiple API calls when a ViewModel is initialised? I was thinking about
init { }
block. The data from these multiple APIs is required to render the initial UI. Also, some of them are dependent on the other APIs response.
s

Stylianos Gakis

03/28/2024, 9:54 AM
Don't do it on init. You're probably gonna have trouble then to re-try if there was a network failure etc. In tests they will run on initialization and not when you want them to. And in the real app, you then don't have a way to stop those requests if there is nobody interested in them anymore (aka nobody is observing the state), but the VM is still alive. Use stateIn() https://github.com/HedvigInsurance/android/blob/develop/app%2Ffeature%2Ffeature-profile%2Fsrc%2Fmain%2Fkotlin%2Fcom%2Fhedvig%2Fandroid%2Ffeature%2Fprofile%2Ftab%2FProfileViewModel.kt#L33-L52 and on the call site use collectAsStateWithLifecycle, or repeatOnLifecycle if you're not doing compose.
m

Mohammed Akram Hussain

03/28/2024, 11:05 AM
Thank you for that but from the above approach how do I handle the case where I need data from
getEuroBonusStatusUseCase
to call
checkTravelCertificateDestinationAvailabilityUseCase
for example? Where I need data from these two APIs to render initial Ui
s

Stylianos Gakis

03/28/2024, 11:15 AM
Just have one use case take as a dependency another use case and do it inside its invoke function. Would that work for you? Then you just call one of them, and internally it can do whatever else it needs to. As far as the initial value goes, the stateIn helps you with forcing you to provide a default value which does not come asynchronously, so there you gotta do some loading state or whatever makes sense for your screen for the first frame(s)
👍 1
5 Views