Last active
May 31, 2020 04:51
-
-
Save chelseatroy/6c8a5b244a5d1ac407ce0ab480e5e405 to your computer and use it in GitHub Desktop.
Interact with API in Activity
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
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