Last active
February 8, 2023 11:06
-
-
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
This file contains hidden or 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.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