Chaiwa Berian
04/22/2022, 11:56 AMqualified this
but I am trying to wrap my brains around this syntax right here:
Observer { loginFormState ->
if (loginFormState == null) {
return@Observer
}
loginButton.isEnabled = loginFormState.isDataValid
loginFormState.usernameError?.let {
usernameEditText.error = getString(it)
}
loginFormState.passwordError?.let {
passwordEditText.error = getString(it)
}
})
I understand the rest of the code except what is happening here:
if (loginFormState == null) {
return@Observer
}
What would be the interpretation of what return@Observer
mean? Semantics?ephemient
04/22/2022, 12:03 PMChaiwa Berian
04/22/2022, 12:11 PMgoto
. Same principal right?ephemient
04/22/2022, 12:15 PMChaiwa Berian
04/22/2022, 12:18 PMcontinue
in other languages?ephemient
04/22/2022, 12:18 PMObserver { ... }
is an anonymous object like
object Observer {
fun observe(loginFormState) {
if (loginFormState == null) {
return
or a function taking a lambda, can't tell without more context, but the code behavior is similar either wayChaiwa Berian
04/22/2022, 12:26 PMloginViewModel.loginFormState.observe(viewLifecycleOwner,
Observer { loginFormState ->
if (loginFormState == null) {
return@Observer
}
loginButton.isEnabled = loginFormState.isDataValid
loginFormState.usernameError?.let {
usernameEditText.error = getString(it)
}
loginFormState.passwordError?.let {
passwordEditText.error = getString(it)
}
})
Chaiwa Berian
04/22/2022, 12:30 PMObserver
and then keeps waiting.Chaiwa Berian
04/22/2022, 12:30 PMephemient
04/22/2022, 12:31 PMChaiwa Berian
04/22/2022, 12:33 PMephemient
04/22/2022, 12:34 PMreturn
always means "return from the enclosing `fun`". there are cases where this is either not the intended behavior (intentional early return within an inline lambda) or impossible (non-inline lambda, SAM/`fun interface`), where you would use return@
. this case is a SAMChaiwa Berian
04/22/2022, 12:36 PMephemient
04/22/2022, 12:36 PMChaiwa Berian
04/22/2022, 12:43 PMObserver
is not a label
but some functional interface and it is being instantiated via lambda expression hence the need to use the return@
in order to return early. Did I now get you right?ephemient
04/22/2022, 12:45 PMreturn
at all, because the observer outlives the functionChaiwa Berian
04/22/2022, 12:46 PM