使用Kotlin高效地開發(fā)Android App(二)

旋轉的樓梯.jpg

上一篇文章介紹了項目中所使用的Kotlin特性,本文繼續(xù)整理當前項目所用到的特性。

一.apply 函數(shù) 和 run 函數(shù)

with、apply、run函數(shù)都是Kotlin標準庫中的函數(shù)。with在第一篇文章中已經(jīng)介紹過。

1.1 apply函數(shù)

apply函數(shù)是指在函數(shù)塊內(nèi)可以通過 this 指代該對象,返回值為該對象自己。在鏈式調用中,可以考慮使用它來不破壞鏈式。

/**
 * Calls the specified function [block] with `this` value as its receiver and returns `this` value.
 */
@kotlin.internal.InlineOnly
public inline fun <T> T.apply(block: T.() -> Unit): T {
    contract {
        callsInPlace(block, InvocationKind.EXACTLY_ONCE)
    }
    block()
    return this
}

舉個例子:

/**
 * Created by tony on 2018/4/26.
 */
object Test {

    @JvmStatic
    fun main(args: Array<String>) {

        val result ="Hello".apply {


            println(this+" World")

            this+" World"
        }

        println(result)
    }
}

執(zhí)行結果:

Hello World
Hello

第一個字符串是在閉包中打印的,第二個字符串是result的結果,它仍然是“Hello”。

1.2 run函數(shù)

run函數(shù)類似于apply函數(shù),但是run函數(shù)返回的是最后一行的值。

/**
 * Calls the specified function [block] with `this` value as its receiver and returns its result.
 */
@kotlin.internal.InlineOnly
public inline fun <T, R> T.run(block: T.() -> R): R {
    contract {
        callsInPlace(block, InvocationKind.EXACTLY_ONCE)
    }
    return block()
}

舉個例子:

/**
 * Created by tony on 2018/4/26.
 */
object Test {

    @JvmStatic
    fun main(args: Array<String>) {

        val result ="Hello".run {


            println(this+" World")

            this + " World"
        }

        println(result)
    }
}

執(zhí)行結果:

Hello World
Hello World

第一個字符串是在閉包中打印的,第二個字符串是result的結果,它返回的是閉包中最后一行的值,所以也打印“Hello World”。

1.3 項目中的使用

在App的反饋頁面中,需要輸入郵箱、主題、內(nèi)容才能完成反饋按鈕的提交。

最初的寫法是這樣:

        if (viewModel.email.value!!.isEmpty()) {
            toast(resources.getString(R.string.you_have_not_completed_the_email_address)).show()
            return@onClickRight
        }
        if (!Util.checkEmail(viewModel.email.value!!)) {
            toast(resources.getString(R.string.the_email_format_you_have_filled_is_incorrect)).show()
            return@onClickRight
        }
        if (viewModel.subject.value!!.isEmpty()) {
            toast(resources.getString(R.string.you_have_not_completed_the_feedback_subject)).show()
            return@onClickRight
        }
        if (viewModel.content.value!!.isEmpty()) {
            toast(resources.getString(R.string.you_have_not_completed_the_details)).show()
            return@onClickRight
        }

修改成只使用apply函數(shù)

       viewModel.apply {

            if (email.value!!.isEmpty()) {
                toast(resources.getString(R.string.you_have_not_completed_the_email_address)).show()
                return@onClickRight
            }
            if (!Util.checkEmail(email.value!!)) {
                toast(resources.getString(R.string.the_email_format_you_have_filled_is_incorrect)).show()
                return@onClickRight
            }
            if (subject.value!!.isEmpty()) {
                toast(resources.getString(R.string.you_have_not_completed_the_feedback_subject)).show()
                return@onClickRight
            }
            if (content.value!!.isEmpty()) {
                toast(resources.getString(R.string.you_have_not_completed_the_details)).show()
                return@onClickRight
            }
        }

感覺不夠cool,可以結合run和apply函數(shù)一起使用

        viewModel.email.run {

            if (value!!.isEmpty()) {
                toast(resources.getString(R.string.you_have_not_completed_the_email_address)).show()
                return@onClickRight
            }
            if (!Util.checkEmail(value!!)) {
                toast(resources.getString(R.string.the_email_format_you_have_filled_is_incorrect)).show()
                return@onClickRight
            }

            viewModel
        }.subject.run {

            if (value!!.isEmpty()) {
                toast(resources.getString(R.string.you_have_not_completed_the_feedback_subject)).show()
                return@onClickRight
            }

            viewModel
        }.content.apply {

            if (value!!.isEmpty()) {
                toast(resources.getString(R.string.you_have_not_completed_the_details)).show()
                return@onClickRight
            }
        }

二.data class

Kotlin的data class有點類似于Scala的case class。

以下的Java Bean代碼

/**
 * Created by tony on 2018/4/27.
 */
public class User {

    public String userName;
    public String password;
}

等價于

data class User (var userName: String? = null,var password: String? = null)

可以看到采用data class能夠簡化Java Bean類。我們的App采用了MVVM的架構,因此對應Model類全部使用data class。

三.無需使用findViewById 或者 butterknife

使用Kotlin Android Extensions插件即可實現(xiàn)該功能,它是Kotlin 插件的組成之一,無需再單獨安裝插件。

我們在各個modules的build.gradle中添加該插件,即可使用。

apply plugin: 'kotlin-android-extensions'

布局文件中的id,可以直接在代碼中使用。
首先,按照import kotlinx.android.synthetic.main.布局文件名*的方式導入。

例如MainActivity,它的布局文件是activity_main.xml
則按照如下的方式進行import

import kotlinx.android.synthetic.main.activity_main.*

那么activity_main.xml中控件的id,可以直接在MainActivity中使用,無需使用findViewById 或者 butterknife。是不是特別方便?

四.點擊事件的埋點處理

App的埋點,使用自己家的產(chǎn)品--魔窗的sdk來做事件的埋點。

如果使用Java來開發(fā)App,可以使用AOP來實現(xiàn)埋點。由于我們的App采用Kotlin編寫,Kotlin可以將事件的點擊簡化成如下的形式

        view.setOnClickListener {
             ....
        }

這種簡化了的lambda表達式,所以我還是老老實實的使用傳統(tǒng)方式進行埋點。

使用Kotlin的通常做法:

        view.setOnClickListener {

             TrackAgent.currentEvent().customEvent(eventName)
             ....
        }

或者

        view.setOnClickListener {

             TrackAgent.currentEvent().customEvent(eventName, trackMap)
             ....
        }

后來,我寫了一個View的擴展函數(shù)click,后來經(jīng)過同事的優(yōu)化。可以查看簡書的這篇文章 利用擴展函數(shù)優(yōu)雅的實現(xiàn)“防止重復點擊”

目前,已經(jīng)將該擴展函數(shù)放入我的Kolin的工具類庫
https://github.com/fengzhizi715/SAF-Kotlin-Utils

此時,埋點的代碼變成這樣

        view.click {

             TrackAgent.currentEvent().customEvent(eventName)
             ....
        }

或者

        view.click {

             TrackAgent.currentEvent().customEvent(eventName, trackMap)
             ....
        }

進一步的優(yōu)化處理,對于View增加擴展函數(shù)clickWithTrack專門用于埋點的點擊事件。

package cn.magicwindow.core.ext

import android.view.View
import cn.magicwindow.TrackAgent
import com.safframework.ext.clickWithTrigger

/**
 *
 * @FileName:
 *          cn.magicwindow.core.ext.ViewExt.java
 * @author: Tony Shen
 * @date: 2018-04-24 17:17
 * @version V1.0 <描述當前版本功能>
 */

fun <T : View> T.clickWithTrack(eventName: String, time: Long = 600, block: (T) -> Unit) = this.clickWithTrigger(time) {

    TrackAgent.currentEvent().customEvent(eventName)
    block(it as T)
}

fun <T : View> T.clickWithTrack(eventName: String, trackMap: HashMap<String, String>, time: Long = 600, block: (T) -> Unit) = this.clickWithTrigger(time) {

    TrackAgent.currentEvent().customEvent(eventName, trackMap)
    block(it as T)
}

此時埋點可以這樣使用:

        view.clickWithTrack(key) {
            ....
        }

或者

        view.clickWithTrack(key,trackMap) {
            ....
        }

總結

Kotlin有很多的語法糖,使用這些語法糖可以簡化代碼以及更優(yōu)雅地實現(xiàn)功能。

該系列的相關文章:
使用Kotlin高效地開發(fā)Android App(五)完結篇
使用Kotlin高效地開發(fā)Android App(四)
使用Kotlin高效地開發(fā)Android App(三)
使用Kotlin高效地開發(fā)Android App(一)

最后編輯于
?著作權歸作者所有,轉載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內(nèi)容