Operator overloading
In Kotlin’s world, we can overload arithmetic operators, including unary, binary, and compound assignment operators.
Use the operator modifier to modify functions with specific function names, which can be member functions or extension functions.
For example, there is such a method in RxKotlin’s disposable. Kt.
operator fun CompositeDisposable.plusAssign(disposable: Disposable) {
add(disposable)
}
Copy the code
It satisfies two conditions:
- Use operator to decorate
- Use plusAssign as the function name
So you can override the compound operator +=, but how do you use it?
compositeDisposable += RxBus.get().register(PaySuccessEvent::class.java) { getServices() }
Copy the code
It is equivalent to the following code
compositeDisposable.add(
RxBus.get().register(PaySuccessEvent::class.java) { getServices() }
)
Copy the code
We’ll find that overloading the operator makes the code look cleaner and more elegant.
2. Simplified lambda expressions
Trailing closures, introduced in Kotlin efficient Development of Android Apps (I), are sort of a simplified lambda expression.
For click events on UI controls, check out my colleague’s article View.onClickListener evolution in Kotlin
From the original Java version
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) { v.setVisibility(View.VISIBLE); . }});Copy the code
Using Kotlin to simplify, it becomes:
view.setOnClickListener {
it.visibility = View.VISIBLE
...
}
Copy the code
Let’s take another example with RxJava.
Observable.just("just a test")
.subscribe(new Consumer<String>() {
@Override
public void accept(String s) throws Exception { System.out.println(s); }},new Consumer<Throwable>() {
@Override
public void accept(Throwable throwable) throws Exception { throwable.printStackTrace(); }});Copy the code
If you use Java lambda to simplify, you can write it like this.
Observable.just("just a test")
.subscribe(s -> {
System.out.println(s);
}, throwable -> {
throwable.printStackTrace();
});
Copy the code
The same code is much easier to write in Kotlin.
Observable.just("just a test")
.subscribe(
{ System.out.println(it) },
{ it.printStackTrace() }
)
Copy the code
3. String processing
Java needs to remember the %d, %s and other converters when using the string. format function. Kotlin is probably referring to Groovy syntax, using ${variable name} is simple and convenient.
Similarly to Groovy, Kotlin also has three double quotes to indicate the output of multiple lines of text.
Such as:
var jsonString: String = """ { "username":"tony", "password":"123456" } """
println(jsonString)
Copy the code
Execution result:
{
"username":"tony"."password":"123456"
}
Copy the code
RxJava and LiveData, Lifecycle
LiveData and Lifecycle are part of Google’s new Android Architecture Components in 2017.
The LiveData component is used to hold observable data. It holds the lifecycle information of the component, provides updates when the component is active, and is typically used to create responsive UIs.
The Lifecycle component is used to create activities and fragments that are aware of their own Lifecycle and can adjust their behavior based on their state. Components can go through multiple states — initialized, created, started, restored, destroyed — and invoke lifecycle methods to perform various actions when the state changes.
With the help of Kotlin extension function and RxJava features, as well as the reference for the library at https://github.com/YvesCheung/LiveDataToRxJava.
I made a LiveData extension library making address: https://github.com/fengzhizi715/LiveDataExtension
Main functions:
-
Support to convert LiveData into Observable and Flowable. This is implemented through the extension functions toObservable() and toFlowable() added to LiveData.
-
Supports conversion of RxJava Observable, Flowbale, Completable, Single, Maybe to LiveData. Through their extension function toLiveData().
-
Support RxJava Observable, Flowbale, Completable, Single, Maybe binding to Lifecycle. Through their extension function bindLifecycle().
For example, in LoginViewModel, the login() function might be written roughly like this, replacing the RxLifecycle function previously used. Of course, the use of RxLifecycle is also intended to avoid memory leaks. Since we already use Android Architecture Components in our App Architecture, we can consider replacing RxLifecycle.
fun login(owner: LifecycleOwner): Observable<LoginResponse> {
val param = LoginParam()
param.phoneNo = phoneNumber.value.toString()
param.zoneCode = zoneCode
param.validationCode = verificationCode.value.toString()
return RetrofitManager.get()
.apiService()
.login(param)
.compose(RxJavaUtils.observableToMain())
.bindLifecycle(owner)
}
Copy the code
conclusion
Kotlin’s many simplified ways of writing make development more efficient and the code cleaner and more elegant.
Related articles in this series:
Use Kotlin to efficiently develop Android App(5) the final part
Developing Android Apps efficiently with Kotlin (part 3)
Developing Android Apps efficiently with Kotlin (part 2)
Developing Android Apps efficiently with Kotlin (1)
Java and Android technology stack: weekly updates push original technical articles, welcome to scan the public qr code below and follow, look forward to growing with you and progress together.