Vivek Modi
05/15/2025, 8:36 PMJoffrey
05/15/2025, 8:37 PMVivek Modi
05/15/2025, 8:44 PMimport kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
suspend fun apiCallOne(): Result<String> = withContext(<http://Dispatchers.IO|Dispatchers.IO>) {
try {
// Simulated network call
Result.success("Token123")
} catch (e: Exception) {
Result.failure(e)
}
}
suspend fun apiCallTwo(token: String): Result<String> = withContext(<http://Dispatchers.IO|Dispatchers.IO>) {
try {
// Simulated dependent network call
Result.success("Data for token: $token")
} catch (e: Exception) {
Result.failure(e)
}
}
suspend fun performChainedApiCalls() {
apiCallOne().fold(
onSuccess = { token ->
apiCallTwo(token).fold(
onSuccess = { finalData ->
println("Success: $finalData")
},
onFailure = { e2 ->
println("Second API failed: ${e2.message}")
}
)
},
onFailure = { e1 ->
println("First API failed: ${e1.message}")
}
)
}
Joffrey
05/15/2025, 9:20 PMVivek Modi
05/15/2025, 10:30 PMJoffrey
05/15/2025, 10:39 PMsuspend fun apiCallOne(): String {
// Simulated network call
delay(300.milliseconds)
return "Token123"
}
suspend fun apiCallTwo(token: String): String {
// Simulated dependent network call
delay(300.milliseconds)
return "Data for token: $token"
}
suspend fun performChainedApiCalls() {
val token = apiCallOne()
val finalData = apiCallTwo(token)
println("Success: $finalData")
}
Joffrey
05/15/2025, 10:42 PMResult
. This is an orthogonal concept. Also, I believe Result
is harmful in this case, it complicates the code a lot. The error handling at a higher level would deal with it anyway. But as I said that's a separate discussion 🙂groostav
05/17/2025, 12:56 AMsuspend
semantics.
And further, It is extremely poor practice to write catch(e: Exception)
pretty much ever. This is almost certainly going to get you into trouble at some point.
is there a reason you want to catch(ex: Exception) { println("failed API call one") }
instead of simply `throw`ing e
?Vivek Modi
05/19/2025, 3:31 PMVivek Modi
05/19/2025, 3:33 PMIt is extremely poor practice to write catch(e: Exception) pretty much ever
? How to find errors if we get any from api?Vivek Modi
05/19/2025, 3:35 PMis there a reason you want to catch(ex: Exception) { println("failed API call one") } instead of simply throwing e?
How do we know if api one fails and what is the cause of error?Joffrey
05/20/2025, 7:20 AMException
. Surely you wouldn't handle ClassCastException
the same as IOException
Vivek Modi
05/20/2025, 9:37 AM