LiveData观察者的Kotlin语法? [英] Kotlin syntax for LiveData observer?
问题描述
在我的HomeActivity
中有以下代码可以使用LiveData
.
I have the following bit of code in my HomeActivity
to use LiveData
.
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// Show the launch splash screen.
//
this.setContentView(R.layout.activity_home)
this.viewModel = ViewModelProviders.of(this).get(HomeViewModel::class.java)
this.viewModel.getUser().observe(this, Observer { user: User? ->
});
}
这似乎可行,但以下部分是什么意思?
While this seems to work, what does the following part mean?
Observer { user: User? ->
}
这必须导致对象符合具有
This must result in an object that conforms to the Observer
interface which has
void onChanged (T t)
https://developer.android.com/reference/android/arch/lifecycle/Observer.html
如何
Observer { user: User? ->
}
使用onChanged
方法产生对象吗?
我不知道将接口名称放在lambda表达式前面意味着什么.
I don't know what putting the name of an interface in front of a lambda expression means.
谢谢!
推荐答案
这称为 SAM转换,该概念有助于与Java 单一抽象方法接口交互,例如你的例子.
This is called SAM Conversion, a concept that helps interacting with Java Single Abstract Method Interfaces like in your example.
以下创建了Runnable
的实现,其中单个抽象方法是run()
:
The following creates an implementation of Runnable
, where the single abstract method is run()
:
val runnable = Runnable { println("This runs in a runnable") }
文档中对此进行了描述: https://kotlinlang.org/docs/reference/java-interop.html#sam-conversions
It’s described in the docs: https://kotlinlang.org/docs/reference/java-interop.html#sam-conversions
或者,更冗长的是使用object
:
Alternatively, but more verbose, would be to use an object
:
val runnable2 = object : Runnable {
override fun run() {
println("This runs in a runnable")
}
}
这两个都是该interface
匿名实现的示例.当然也可以创建一个具体的子类,然后实例化它.
Both are examples of anonymous implementations of that interface
. It's of course also possible to create a concrete subclass and instantiate it then.
class MyRunnable : Runnable {
override fun run() {
println("This runs in a runnable")
}
}
val runnable3 = MyRunnable()
这篇关于LiveData观察者的Kotlin语法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!