Skip to content

Instantly share code, notes, and snippets.

@vipinhelloindia
Last active August 18, 2022 16:27
Show Gist options
  • Save vipinhelloindia/a0c0fa673814cd7dfc1f040f02fa60db to your computer and use it in GitHub Desktop.
Save vipinhelloindia/a0c0fa673814cd7dfc1f040f02fa60db to your computer and use it in GitHub Desktop.
/* Avoid hardcoded dispatchers */
class BackgroundExecutor constructor(val contextProvider: ContextProvider) {
companion object {
private val backgroundExecutor = CoroutineScope(SupervisorJob() + Dispatchers.IO)
var executor: ExecutorService = Executors.newFixedThreadPool(5)
private val mainThreadHandler: Handler = Handler(Looper.getMainLooper())
fun <R> executeInMainThread(@NonNull callable: Callable<R>) {
mainThreadHandler.post(Runnable {
callable.call()
})
}
@JvmStatic
fun <R> executeInCoroutine(
callable: Callable<R>
): Job {
return backgroundExecutor.launch {
callable.call()
}
}
@JvmStatic
fun <T> executeInThread(
callable: Callable<T>
): Future<T> {
return executor.submit(callable);
}
@JvmStatic
public fun <R> executeAsFlow(
callable: Callable<R>
): Flow<R> = flow {
backgroundExecutor.launch {
val result = callable.call()
emit(result)
}
}
}
fun <R> enqueueUniquePeriodicWorkByTag(callable: Callable<R>) {
WorkManager.getInstance(contextProvider.get()).enqueueUniquePeriodicWork(
BackgroundWorker.TAG,
ExistingPeriodicWorkPolicy.KEEP,
getBackgroundWorkerRequest(callable)
)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment