Whereas experimenting LiveData
observer, I encountered the next code and I had no thought the way it works.
val observer = Observer<T> {
state.worth = it
}
So I appeared on the Observer
supply code in Java. It appears like this.
public interface Observer<T> {
void onChanged(T t);
}
Observer
is an interface, and observer
is an object that implements the Observer
interface. Wait, the place is override enjoyable onChanged(t: T)
? How is that doable?
It seems that is known as SAM conversions. SAM stands for Single Summary Interface.
Earlier than we glance into SAM conversions, let’s first take a look at alternative ways of implementing the interfaces.
Subclass Standard Technique
That is the interface,
interface Observer<T> {
enjoyable onChanged(t: T)
}
and we subclass it with ObserverImpl
class ObserverImpl<T> : Observer<T> {
override enjoyable onChanged(t: T) {
println("$t")
}
}
To instantiate the ObserverImpl
, name the onChanged()
operate:
val observer = ObserverImpl<String>()
observer.onChanged("take a look at")
Object Key phrase
Apart from creating singleton class, object
key phrase will also be used to implement an interface.
As a substitute of subclassing, you’ll be able to implement the Observer
interface immediately
val observer = object: Observer<String> {
override enjoyable onChanged(t: String) {
println("$t")
}
}
observer.onChanged("take a look at")
SAM Conversions
Earlier than we will use SAM conversions, it is advisable to add enjoyable
key phrase in entrance of the interface
.
enjoyable interface Observer<T> {
enjoyable onChanged(t: T)
}
That is known as Purposeful Interface or Single Summary Technique (SAM) Interface. In different phrase, the interface should have solely ONE operate/methodology.
To implement the Observer
interface, you employ the lambda expression.
val observer = Observer<String> {
println("$it")
}
observer.onChanged("take a look at")
This lambda expression is mainly the override onChanged()
operate that you just need to implement. it
is the implement argument.
If onChanged()
has 2 arguments,
enjoyable interface Observer<T> {
enjoyable onChanged(arg1: T, arg2: T)
}
it will be like this
val observer = Observer<String> { arg1, arg2 ->
println("$arg1,$arg2")
}
observer.onChanged("test1", "test2")
Conclusion
Properly, SAM conversions are new to me. After getting used to it, I simply must think about the lambda expression because the override operate of the interface I need to implement.
It makes use of much less code than object key phrase since you now not must explicitly declare the override operate. The limitation is the interface should include just one interface.