I use a lambda to handle callbacks from an asynchronous call. I'd like to define the callback outside the calling method to avoid a bulky method, but I can't seem to use early returns within the lambda, which makes the code unnecessarily difficult to read.
I've tried defining the lambda as a variable but returns are not viable inside the lambda.
I've tried defining the lambda inside a function and returning but returns were not viable there either.
For example:
private fun onDataUpdated(): (Resource<List<Int>>) -> Unit = {
if (it.data.isNullOrEmpty()) {
// Handle no data callback and return early.
return@onDataUpdated // This is not allowed
}
// Handle the data update
}
}
I've also tried:
private val onDataUpdated: (Resource<List<Int>>) -> Unit = {
if (it.data.isNullOrEmpty()) {
// Handle no data callback and return early.
return // This is not allowed
}
// Handle the data update
}
}
I'd like to perform an early return instead of using an else case, to avoid unnecessary indent, but I can't seem to find a way to use returns inside a lambda.