Skip to content

Instantly share code, notes, and snippets.

@brady-aiello
Last active September 3, 2021 20:50
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save brady-aiello/efe2c6694206945dd832df9b61287a22 to your computer and use it in GitHub Desktop.
Save brady-aiello/efe2c6694206945dd832df9b61287a22 to your computer and use it in GitHub Desktop.
Facebook Login with Coroutines
@ExperimentalCoroutinesApi
private fun setupFacebookContinueButton() {
binding?.buttonContinueFacebook?.setOnClickListener {
beginLoginToFacebook()
finishFacebookLogin { loginResult ->
loginViewModel.loginFacebook(loginResult.accessToken.token)
}
}
}
private fun beginLoginToFacebook() {
if (activity != null) {
LoginManager.getInstance()
.logInWithReadPermissions(activity, listOf("email"))
}
}
@ExperimentalCoroutinesApi
suspend fun getFacebookToken(): LoginResult =
suspendCancellableCoroutine { continuation ->
LoginManager.getInstance()
.registerCallback(loginViewModel.callbackManager, object : FacebookCallback<LoginResult> {
override fun onSuccess(loginResult: LoginResult) {
continuation.resume(loginResult){ }
}
override fun onCancel() {
// handling cancelled flow (probably don't need anything here)
continuation.cancel()
}
override fun onError(exception: FacebookException) {
// Facebook authorization error
continuation.resumeWithException(exception)
}
})
}
@ExperimentalCoroutinesApi
fun FragmentActivity.finishFacebookLoginToThirdParty(
onCredential: suspend (LoginResult) -> Unit
) {
this.lifecycleScope.launchWhenStarted {
try {
val loginResult: LoginResult = getFacebookToken(loginViewModel.callbackManager)
onCredential(loginResult)
} catch (e: FacebookException) {
Log.e("Facebook Error", e.toString())
}
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
loginViewModel.callbackManager.onActivityResult(requestCode, resultCode, data)
// onActivityResult() is deprecated, but Facebook hasn't added support
// for the new Result Contracts API yet.
// https://github.com/facebook/facebook-android-sdk/issues/875
super.onActivityResult(requestCode, resultCode, data)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment