简体   繁体   中英

LiveData map transformations in kotlin

Transformations.map in LiveData transformations take two arguments :

  1. @NonNull LiveData source
  2. @NonNull final Function func

I tried to make the function like this:

val localLiveData = #some live data of type LiveData<User>
Transformations.map(localLiveData, s->{return s.name = "Hi"})

but this shows error cannot unresolved "s"

finally i got it working by this :

Transformations.map(localLiveData) {
              s.name = "Hi"
                return@map s
            }

How this thing is working map has only one argument? (noob in kotlin)

Most of the problems here are with Kotlin's lambda syntax, which is slightly different from that of some other languages.

In Kotlin, a lambda must have braces. But the -> is optional in some cases (if the lambda takes no parameters; or if it takes one and you're referring to it with the dummy name it ).

This is one reason why your first version fails; it would need the s -> moved inside the braces. (Another is that in Kotlin, an assignment is not an expression, and doesn't return a value, so you can't use it in a return .)

Your second works because in Kotlin, if the last parameter is a lambda, it can be moved outside the parenthesis. (This allows for higher-order functions that look like language syntax. In fact, if the lambda is the only parameter, you can omit the parentheses entirely!)

I don't know LiveData, but I wonder if the return@map is doing the right thing: it will return not just from the lambda, but from the map() method itself. (Such non-local returns aren't needed very often, and can be confusing.)

Also, a lambda doesn't need an explicit return ; it returns the value of its last expression.

So I suspect that a more concise version would be:

Transformations.map(localLiveData) { it.name = "Hi"; it }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM