In Java Android, to achieve sequential behavior without blocking main thread, this is the code I am using.
Java Android
private static final ExecutorService executor = Executors.newSingleThreadExecutor();
executor.execute(() -> task0());
executor.execute(() -> task1());
executor.execute(() -> task2());
The above code, will always execute in the exact order of task0
, task1
and task2
functions regardless what is happening inside the functions.
I am impressed by the life cycle aware feature, offered by Kotlin's LifecycleScope. I try to write the code in the following Kotlin's LifecycleScope form.
Kotlin Android
val dispatcherForCalendar = Executors.newSingleThreadExecutor().asCoroutineDispatcher()
lifecycleScope.launch(dispatcherForCalendar) {
task0()
}
lifecycleScope.launch(dispatcherForCalendar) {
task1()
}
lifecycleScope.launch(dispatcherForCalendar) {
task2()
}
The above code will executed in the exact order of task0
, task1
and task2
functions, except when delay is performed in the functions.
- In reality, I will not insert
delay
code explicitly in task functions. In such a case, can Android system still performdelay
operation implicitly? - How I can achieve sequential behavior, same as my Java code
Executors.newSingleThreadExecutor
?
Thank you.