Last active
April 13, 2023 02:19
-
-
Save vic797/7d7e08b3db847de3a61308c9b2f50c9d to your computer and use it in GitHub Desktop.
Async loader in Kotlin
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
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