Hi, My Android app uses Ktor for network requests,...
# android-architecture
k
Hi, My Android app uses Ktor for network requests, and I have a separate module for handling API calls. I've implemented 401 error handling to trigger a logout. However, my navigation logic, including the NavHost, is in the app module. What's the best way to signal the NavHost to perform the logout action when a 401 error occurs?
m
Do you use Result<T> (https://kotlinlang.org/api/core/kotlin-stdlib/kotlin/-result/) as the http api response? the 401 error can be converted to a Result.failure and returned to the navhost using the ui state you've defined
v
do you have any example?
e
Without knowing much about your code base. In your
ViewModel
or where ever you're calling a function to make a network call that will cause the
401
, you could catch the exception that would be thrown and then check to make sure it's an exception due to a
401
then react to it by sending an event or UI state to the UI to cause a logout or directly logout from there – where you are catching the
401
error. See this sample implementation in the Tivi app for an example: https://github.com/chrisbanes/tivi/blob/main/ui/root/src/commonMain/kotlin/app/tivi/home/RootViewModel.kt#L50
👍 1
k
Thank you so much. I'll take a look on that.
👍 1
a
You can keep a singleton state flow named like "AuthenticationStatus" and have a sealed class like object NotAuthenticated: AuthenticationStatus data class Authenticated(val user: User): AuthenticationStatus object SignedOut: AuthenticationStatus .... Then listen this flow in some top level viewmodel has access to a navigation manager and you can emit state from api level
👍 1