Skip to content

Instantly share code, notes, and snippets.

@projectdelta6
Last active February 8, 2023 11:06
Show Gist options
  • Save projectdelta6/e433fccda43756264267ddfc7c0051ed to your computer and use it in GitHub Desktop.
Save projectdelta6/e433fccda43756264267ddfc7c0051ed to your computer and use it in GitHub Desktop.
SetupHandler construct to handle waiting for 2 async tasks to complete before triggering its action
import android.os.Handler
import android.os.Looper
import android.os.Message
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import java.lang.ref.WeakReference
import java.util.concurrent.atomic.AtomicBoolean
class SetupHandler(onSetupComplete: OnSetupComplete): Handler(Looper.getMainLooper()) {
private val weakReference: WeakReference<OnSetupComplete> = WeakReference(onSetupComplete)
private val uiComplete = AtomicBoolean(false)
private val backgroundComplete = AtomicBoolean(false)
override fun handleMessage(msg: Message) {
when(msg.what) {
UI_Complete -> {
uiComplete.set(true)
}
Background_Complete -> {
backgroundComplete.set(true)
}
}
if(uiComplete.get() && backgroundComplete.get()) {
weakReference.get()?.onSetupComplete()
}
}
fun sendUiComplete() {
sendEmptyMessage(UI_Complete)
}
@JvmOverloads
fun doInBackground(
dispatcher: CoroutineDispatcher = Dispatchers.Default,
backgroundTask: suspend () -> Unit
) {
CoroutineScope(dispatcher).launch {
backgroundTask.invoke()
}
}
fun doInBackground(
coroutineScope: CoroutineScope,
backgroundTask: suspend () -> Unit
) {
coroutineScope.launch {
backgroundTask.invoke()
}
}
fun sendBackgroundComplete() {
sendEmptyMessage(Background_Complete)
}
fun resetBackgroundState() {
backgroundComplete.set(false)
}
companion object {
private const val UI_Complete = 1
private const val Background_Complete = 2
}
interface OnSetupComplete {
fun onSetupComplete()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment