Last active
August 18, 2022 16:27
-
-
Save vipinhelloindia/a0c0fa673814cd7dfc1f040f02fa60db to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* 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