Kotlin的扩展,闭包

972 阅读1分钟

GSON扩展

用法

/**
 * 通过reified字段去推断类型
 * 用法:
 *      val articleData: ArticleData = gson.fromJson("jsonString")
 * 或者
 *      gson.fromJson<ArticleData>("jsonString")
 */

扩展

val gson: Gson by lazy {
    Gson()
}
inline fun <reified T> Gson.fromJson(json: String): T =
    fromJson(json, T::class.java)

ImageView加载图片扩展

用法

mImageView.loadUrl("图片地址")

扩展

fun ImageView.loadUrl(img: String="") {
    Glide.with(ApplicationsTools.context()).load(img).into(this)
}

页面跳转

用法

startNewActivity<Activity>()
或者
startNewActivity<Activity>(
       bundle {
           putString("name", "First")
           putString("age", "12")
       })

扩展

inline fun <reified T : Activity> Activity.startNewActivity(bundle: Bundle = bundle()) {
    var intent = Intent(this, T::class.java)
    intent.putExtras(bundle)
    startActivity(intent)
}

fun bundle(callback: (Bundle.() -> Unit) = {}): Bundle {
    val bundle = Bundle()
    callback(bundle)
    return bundle
}

协程的切换,从IO协程切换到Main线程

用法

launchIOToMain({
            Log.e("zxy", "123")
            delay(6000)
            Log.e("zxy", "456")
            "123"
        }, {
            Log.e("zxy", "同步主线程")
        }, {
            Log.e("zxy", "异常")
        })

扩展

fun <T> launchIOToMain(
    block:  suspend CoroutineScope.() -> T,
    callback:(T) -> Unit,
    error: ((Exception) -> Unit) = {}
): Job {
    return GlobalScope.launch {
        try {
            val data = withContext(Dispatchers.IO) { //协程切换,得到IO协程的泛型结果
                block()
            }
            withContext(Dispatchers.Main) {//协程切换主协程
                callback(data)
            }
        } catch (e: Exception) {
            withContext(Dispatchers.Main) {//异常
                error.invoke(e)
            }
        }
    }
}