Whereas experimenting LiveData
observer, I encountered the next code and I had no concept the way it works.
val observer = Observer<T> {
state.worth = it
}
So I seemed on the Observer
supply code in Java. It seems to be 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 potential?
It seems that is referred to as SAM conversions. SAM stands for Single Summary Interface.
Earlier than we glance into SAM conversions, let’s first take a look at other ways of implementing the interfaces.
Subclass Standard Methodology
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()
perform:
val observer = ObserverImpl<String>()
observer.onChanged("check")
Object Key phrase
Aside from creating singleton class, object
key phrase will also be used to implement an interface.
As a substitute of subclassing, you possibly can implement the Observer
interface instantly
val observer = object: Observer<String> {
override enjoyable onChanged(t: String) {
println("$t")
}
}
observer.onChanged("check")
SAM Conversions
Earlier than we will use SAM conversions, it’s essential to add enjoyable
key phrase in entrance of the interface
.
enjoyable interface Observer<T> {
enjoyable onChanged(t: T)
}
That is referred to as Useful Interface or Single Summary Methodology (SAM) Interface. In different phrase, the interface will need to have solely ONE perform/methodology.
To implement the Observer
interface, you employ the lambda expression.
val observer = Observer<String> {
println("$it")
}
observer.onChanged("check")
This lambda expression is mainly the override onChanged()
perform that you simply need to implement. it
is the implement argument.
If onChanged()
has 2 arguments,
enjoyable interface Observer<T> {
enjoyable onChanged(arg1: T, arg2: T)
}
it’s going to 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 perform of the interface I need to implement.
It makes use of much less code than object key phrase since you not must explicitly declare the override perform. The limitation is the interface should include just one interface.