54 lines
1.7 KiB
Kotlin
54 lines
1.7 KiB
Kotlin
package com.gh.common
|
|
|
|
import android.os.Handler
|
|
import android.os.Looper
|
|
import com.gh.common.AppExecutor.ioExecutor
|
|
import com.gh.common.AppExecutor.lightWeightIoExecutor
|
|
import com.gh.common.AppExecutor.uiExecutor
|
|
import io.reactivex.schedulers.Schedulers
|
|
import java.util.concurrent.Executor
|
|
import java.util.concurrent.Executors
|
|
|
|
/**
|
|
* APP 线程池管理类
|
|
*
|
|
* [ioExecutor] 是一个最大线程数固定的线程池,较为繁重的 IO 任务可以交给它
|
|
* [uiExecutor] 是主线程的包裹,需要切换至主线程执行可以用它
|
|
* [lightWeightIoExecutor] 是一个单线程的线程池,轻量级且需要保证同一线程的 IO 任务可以交给它
|
|
*
|
|
*/
|
|
object AppExecutor {
|
|
|
|
@JvmStatic
|
|
val uiExecutor by lazy { MainThreadExecutor() }
|
|
@JvmStatic
|
|
val lightWeightIoExecutor by lazy { Executors.newSingleThreadExecutor() }
|
|
@JvmStatic
|
|
val ioExecutor = Executors.newCachedThreadPool() // 用 by lazy 可能影响初始化速度
|
|
|
|
val cachedScheduler by lazy { Schedulers.from(ioExecutor) }
|
|
|
|
class MainThreadExecutor : Executor {
|
|
private val mainThreadHandler = Handler(Looper.getMainLooper())
|
|
|
|
override fun execute(command: Runnable) {
|
|
mainThreadHandler.post(command)
|
|
}
|
|
|
|
fun executeWithDelay(command: Runnable, delay: Long) {
|
|
mainThreadHandler.postDelayed(command, delay)
|
|
}
|
|
}
|
|
}
|
|
|
|
fun runOnIoThread(isLightWeightTask: Boolean = false, f: () -> Unit) {
|
|
if (isLightWeightTask) {
|
|
AppExecutor.lightWeightIoExecutor.execute(f)
|
|
} else {
|
|
AppExecutor.ioExecutor.execute(f)
|
|
}
|
|
}
|
|
|
|
fun runOnUiThread(f: () -> Unit) {
|
|
AppExecutor.uiExecutor.execute(f)
|
|
} |