Skip to content

Instantly share code, notes, and snippets.

@ryohji
Last active October 9, 2019 16:43
Show Gist options
  • Save ryohji/248897d314ffcaf82eb3633c727c5ca5 to your computer and use it in GitHub Desktop.
Save ryohji/248897d314ffcaf82eb3633c727c5ca5 to your computer and use it in GitHub Desktop.
Executor implementation for PagedList.Builder's setFetchExecutor and setNotifyExecutor.
object Executor {
val uiExecutor = Handler(Looper.getMainLooper()).toExecutor()
val ioExecutor = LooperThread().also { it.start() }.getHandler().toExecutor()
private fun Handler.toExecutor(): Executor = Executor {
while (!post(it)) {
Thread.sleep(0)
}
}
private class LooperThread : Thread("sub looper") {
private var handler: Handler? = null
private val lock = ReentrantLock()
private val cond = lock.newCondition()
override fun run() {
Looper.prepare()
lock.withLock {
handler = Handler()
cond.signalAll()
}
Looper.loop()
}
fun getHandler() = lock.withLock {
if (handler == null) {
cond.await()
}
handler!!
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment