Kotlin and Reactive Extensions (Rx) are the new hotness in Android development, and not without reason. Both technologies are loved for being concise, expressive and powerful. This is especially useful in the Android world where APIs can be long-winded and filled with ceremony.
One of the main features that I've fallen in love with while using Kotlin is class extensions (docs). This feature comes in handy quite often when working with APIs that are not yet RxJava compatible in a project that is using RxJava extensively.
Let's take a look at a simple example when using the SlidingUpPanel library.
Basic API Usage
One of the things you might want to do when using this library is listen for panel events such as expanding and collapsing of the panel.
When doing this without RxJava you get the following codeblock
1 | slidingUpPanel.setPanelSlideListener(object: SlidingUpPanelLayout.PanelSlideListener { |
This is a required implementation when you might only care about the expanded and collapsed state.
Kotlin Extension
So, lets move this into a Kotlin extension:
We're going to start with a data class to model the panel events:
1 | enum class PanelEvent { COLLAPSED, EXPANDED, HIDDEN, ANCHORED, SLIDE } |
Now the actual class extension:
1 | fun SlidingUpPanelLayout.panelSlides() : Observable<PanelData> { |
And the calling code:
1 | slidingUpPanel.panelSlides() |
Now you have the power of RxJava's composibility and concise syntax availble to you, without losing the context of the action itself.
Java Interop
Because of Kotlin and Java's interoperability we can also use this extension from Java code as a "Util" class.
Add the following to the top of the extension file (otherwise it'll use <FileName>Kt
as the classname)
1 | @file:JvmName("SlidingUpPanelLayoutUtils") |
And now from java code you can do the following
1 | SlidingUpPanelLayoutUtils.panelSlides(slidingUpPanelLayout) |
For more examples, checkout RxBinding which has extensions for Android framework classes.