Using default named arguments and lambda expressions can be really useful in Android. Let's look at some practical Android examples. Let's suppose we have a function that downloads elements and shows them to the user. We will add a few parameters:
onStart
: This will be called before the network operationonFinish
: This will be called after the network operation
fun getAndFillList(onStart: () -> Unit = {}, onFinish: () -> Unit = {}){ // code }
Then, we can show and hide the loading spinner in onStart
and onFinish
:
getAndFillList( onStart = { view.loadingProgress = true } , onFinish = { view.loadingProgress = false } )
If we start it from swipeRefresh
, then we just need to hide it when it finishes:
getAndFillList(onFinish = { view.swipeRefresh.isRefreshing = false })
If we want to make a quiet refresh, then we just call this:
getAndFillList()
Named argument syntax and lambda expressions...