kotlin 线程切换工具
2020-01-09 本文已影响0人
折剑游侠
这里先不说协程,前面讲过java线程池,kotlin扩展函数。
封装一下工具类
private val handler = Handler(Looper.getMainLooper())
private val coreSize = Runtime.getRuntime().availableProcessors() + 1
private val fix: ExecutorService = Executors.newFixedThreadPool(coreSize)
private val cache: ExecutorService = Executors.newCachedThreadPool()
private val single: ExecutorService = Executors.newSingleThreadExecutor()
private val scheduled: ExecutorService = Executors.newScheduledThreadPool(coreSize)
/**
* 切换到主线程
*/
fun <T> T.ktxRunOnUi(block: T.() -> Unit) {
handler.post {
block()
}
}
/**
* 延迟delayMillis后切换到主线程
*/
fun <T> T.ktxRunOnUiDelay(delayMillis: Long, block: T.() -> Unit) {
handler.postDelayed({
block()
}, delayMillis)
}
/**
* 子线程执行。SingleThreadPool
*/
fun <T> T.ktxRunOnBgSingle(block: T.() -> Unit) {
single.execute {
block()
}
}
/**
* 子线程执行。FixedThreadPool
*/
fun <T> T.ktxRunOnBgFix(block: T.() -> Unit) {
fix.execute {
block()
}
}
/**
* 子线程执行。CachedThreadPool
*/
fun <T> T.ktxRunOnBgCache(block: T.() -> Unit) {
cache.execute {
block()
}
}
如此一来,任意地方都可以切换线程。加上泛型T的好处是lambda内部this指向调用者。
btHome.setSingleClick {
btHome.ktxRunOnUi {
val text = this.text.toString()
}
}
this就是btHome这个view了。