Last active
May 31, 2018 07:37
-
-
Save tinsukE/be16eda2c49f5d9f642229485024999d to your computer and use it in GitHub Desktop.
Coroutines Splash
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
class SplashActivity : Activity() { | |
private val creationTime = System.currentTimeMillis() | |
private var splashJob: Job? = null | |
override fun onCreate(savedInstanceState: Bundle?) { | |
super.onCreate(savedInstanceState) | |
initializeApp() | |
} | |
private fun initializeApp() { | |
splashJob?.cancel() | |
splashJob = launch(UI) { | |
try { | |
// For each task, create a child coroutine | |
val userSessionJob = async(coroutineContext) { userSession.init() } | |
val supportInfoJob = async(coroutineContext) { supportInfoHelper.updateInfo() } | |
// Just calling delay(MIN_SHOW_TIME) would be incorrect for retries | |
val delayTime = (creationTime + MIN_SHOW_TIME) - System.currentTimeMillis() | |
if (delayTime > 0) { | |
delay(delayTime) | |
} | |
// Calling this a second time is not a problem | |
progressBar.visibility = View.VISIBLE | |
// By await'ing after creating all child coroutines we make | |
// sure that they can run in parallel | |
userSessionJob.await() | |
supportInfoJob.await() | |
// All good, we're done | |
setResult(Activity.RESULT_OK) | |
finish() | |
} catch (error: Error) { | |
showRetryAlert(error, | |
onRetry = { initializeApp() }, | |
onCancel = { finish() }) | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment