Skip to content

Instantly share code, notes, and snippets.

@vic797
Last active April 13, 2023 02:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vic797/7d7e08b3db847de3a61308c9b2f50c9d to your computer and use it in GitHub Desktop.
Save vic797/7d7e08b3db847de3a61308c9b2f50c9d to your computer and use it in GitHub Desktop.
Async loader in Kotlin
import android.util.Log
import kotlinx.coroutines.*
import androidx.core.util.Consumer
import org.greenrobot.eventbus.EventBus
import xyz.binary.foxlauncher.data.event.LoadingStateEvent
abstract class Loader<Params, Progress, Result>(
private val finalizer: Consumer<Result>?
) {
constructor() : this(null)
@OptIn(DelicateCoroutinesApi::class)
fun load(vararg params: Params) {
if (beforeLoad(*params)) {
val exceptionHandler = CoroutineExceptionHandler { _, ex ->
Log.e("CoroutineScope", "Caught ${Log.getStackTraceString(ex)}")
handleException(ex)
}
GlobalScope.launch(exceptionHandler) {
val result = doLoad(*params)
withContext(Dispatchers.Main) {
afterLoad(result)
}
}
}
}
private fun handleException(e: Throwable) {
runBlocking {
withContext(Dispatchers.Main) {
handledException(e)
}
}
}
protected open fun handledException(e: Throwable) {
e.printStackTrace()
}
protected open fun beforeLoad(vararg params: Params): Boolean {
EventBus.getDefault().post(LoadingStateEvent(true))
return true
}
protected suspend fun postProgress(item: Progress) {
withContext(Dispatchers.Main) {
onProgress(item)
}
}
protected open fun onProgress(item: Progress) {}
protected abstract fun doLoad(vararg params: Params): Result
protected open fun afterLoad(result: Result) {
EventBus.getDefault().post(LoadingStateEvent(false))
finalizer?.accept(result)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment