简体   繁体   English

kotlin中的LiveData地图转换

[英]LiveData map transformations in kotlin

Transformations.map in LiveData transformations take two arguments : LiveData转换中的Transformations.map有两个参数:

  1. @NonNull LiveData source @NonNull LiveData源码
  2. @NonNull final Function func @NonNull最终函数函数

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" 但这显示错误无法解决“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) (kotlin的noob)

Most of the problems here are with Kotlin's lambda syntax, which is slightly different from that of some other languages. 这里的大多数问题都是Kotlin的lambda语法,它与其他一些语言略有不同。

In Kotlin, a lambda must have braces. 在Kotlin,一个lambda必须有括号。 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 ). 但是->在某些情况下是可选的(如果lambda没有参数;或者如果它需要一个,你用虚拟名称引用it )。

This is one reason why your first version fails; 这是您的第一个版本失败的原因之一; it would need the s -> moved inside the braces. 它需要s ->在支架内移动。 (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 .) (另一个是在Kotlin中,赋值不是表达式,并且不返回值,因此您不能在return使用它。)

Your second works because in Kotlin, if the last parameter is a lambda, it can be moved outside the parenthesis. 你的第二个工作是因为在Kotlin中,如果最后一个参数是lambda,它可以移到括号之外。 (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!) (这允许看起来像语言语法的高阶函数。事实上,如果lambda是唯一的参数,你可以完全省略括号!)

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. 我不知道LiveData,但我想知道return@map是否做了正确的事情:它不仅会从lambda返回,还会从map()方法本身返回。 (Such non-local returns aren't needed very often, and can be confusing.) (这种非本地回报不是经常需要的,而且可能令人困惑。)

Also, a lambda doesn't need an explicit return ; 此外,lambda不需要显式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 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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