NOTE: This repository has been deprecated. Use kotlin coroutine
AndroidThreadSwitcher
helps you to switch between UI thread and Worker thread easily. It would free you from a lot of boilerplate codes and the Callback Hell.
Add the following to app
's build.gradle
file:
dependencies {
implementation 'boxresin.library:AndroidThreadSwitcher:1.2.0'
}
ThreadSwitcher.newChain() // Create an empty chain.
// Concat a UI chain to the empty chain.
.onUI {
// Some tasks to do on a UI Thread
"result" // Pass any value to the next chain.
}
// Concat a Worker chain to the previous chain.
.onWorker { result: String -> // Receive the value from the previous chain.
// Some tasks to do on Worker Thread
}
.onUI {
// Some tasks to do on a UI Thread
}
.onWorker {
// Some tasks to do on a Worker Thread
"data"
}
// Start to perform all chains from the top to bottom.
.start(
// onSuccess callback would be invoked when all chains are finished without any exception.
onSuccess = { result: String -> // The type of parameter is settled by the return value of last chain.
},
// onError callback would be invoked when an exception occurred during performancing chains.
onError = { e: Throwable -> // The exception
})
ThreadSwitcher.newChain() // Create an empty chain.
// Concat a UI chain to the empty chain.
.onUI(v -> // v is Void type.
{
// Some tasks to do on a UI Thread
return "result"; // Pass any value to the next chain.
})
// Concat a Worker chain to the previous chain.
.onWorker((String result) -> // Receive the value from the previous chain.
{
// Some tasks to do on Worker Thread
return Unit.INSTANCE; // Unit type of Kotlin
})
.onUI(unit -> // Unit type of Kotlin
{
// Some tasks to do on a UI Thread
return Unit.INSTANCE;
})
.onWorker(unit ->
{
// Some tasks to do on a Worker Thread
return "data";
})
// Start to perform all chains from the top to bottom.
.start(
// This function would be invoked when all chains are finished without any exception.
(String result) -> { // The type of parameter is settled by the return value of last chain.
return Unit.INSTANCE;
},
// This function would be invoked when an exception occurred during performancing chains.
(Throwable e) -> {
return Unit.INSTANCE;
}
);