Skip to content

Instantly share code, notes, and snippets.

@chelseatroy
Last active May 31, 2020 04:51
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 chelseatroy/6c8a5b244a5d1ac407ce0ab480e5e405 to your computer and use it in GitHub Desktop.
Save chelseatroy/6c8a5b244a5d1ac407ce0ab480e5e405 to your computer and use it in GitHub Desktop.
Interact with API in Activity
class LoginActivity : AppCompatActivity() {
...
fun authenticate() {
val loginJob = Job()
val errorHandler = CoroutineExceptionHandler { _, exception ->
AlertDialog.Builder(this).setTitle("Error")
.setMessage(exception.message)
.setPositiveButton(android.R.string.ok) { _, _ -> }
.setIcon(android.R.drawable.ic_dialog_alert).show()
}
val coroutineScope = CoroutineScope(loginJob + Dispatchers.Main)
var session: CanarySession? = null
coroutineScope.launch(errorHandler) {
session = MockyAPIImplementation().authenticate()
//DON'T ACTUALLY log people's authentication tokens in a production application
Log.i("Session Retrieved:", session.toString())
if (session?.token != null) {
startActivity(Intent(this@LoginActivity, MainActivity::class.java))
} else {
deliverAuthFailureMessage()
}
}
}
private fun deliverAuthFailureMessage() {
AlertDialog.Builder(this).setTitle("Whoops")
.setMessage("Wrong credentials. Try again?")
.setPositiveButton(android.R.string.ok) { _, _ -> }
.setIcon(android.R.drawable.ic_dialog_alert).show()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment