How to handle RESULT_CANCELED state of registerForActivityResult in ViewModel

172 Views Asked by At

I want to perform an operation on canceled state of registerForActivityResult in ViewModel from the MainActivity.

override val resultLauncher =
    registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
        val tag = "Result Launcher"
        if (result.resultCode == Activity.RESULT_OK) {
            val data: Intent? = result.data
            val resp = AuthorizationResponse.fromIntent(data!!)
            val ex = AuthorizationException.fromIntent(data)


            resp?.let { response ->
                response.authorizationCode?.let { code ->
                    appLoggerRepresentable.log.debug(tag, "Auth code: $code")
                }
                loginUtility.renewToken(response)
            }

            ex?.let {
                appLoggerRepresentable.log.debug(tag, "Auth Exception: $it")
            }
        } else {
            appLoggerRepresentable.log.debug(
                tag,
                "Result != Activity.RESULT_OK, need to handle failure."
            )
        }
    }

And this is my interface

interface LoginUtilityRepresentable {
fun signOff(context: Context)
fun presentLogin(activityToPresentFrom: ActivityWithLoginLaunchersRepresentable, callback: (Boolean, Throwable?) -> Unit)
fun renewToken(resp: AuthorizationResponse)
}

And here is the code to handle RESULT_OK state. Now I want handle here RESULT_CANCELED status and perform my own action.

weakReferenceActivity?.get()?.let { activity ->
            loginUtility.presentLogin(activity as MainActivity) { didLogin, _, exception ->
                if (didLogin) {
                    loggerRepresentable.log.debug(
                        mTAG,
                        "Needs Login, user logged in with SSO, checking location data."
                    )
                    navHostController.navigate(Screens.MAINMENU.screenName)
                    hideProgressBar()
                } else {
                    showErrorMessage(exception)
                    hideProgressBar()
                }
            }
        }
0

There are 0 best solutions below