Search code examples
javaandroidamazon-cognitoaws-amplify

Amplify Auth events don't work in android


I'm working in on an app that uses authentication from the AWS Amplify library. I tried to check the sign-in state by looking at Amplify's auth events, but it doesn't work. I tried to verify with logcat, but it only shows me the output of the fetch.

Amplify.Auth.fetchAuthSession(
    result -> Log.i("AmplifyQuickstart", result.toString()),
    error -> Log.e("AmplifyQuickstart", error.toString())
);

Amplify.Hub.subscribe(HubChannel.AUTH, hubEvent -> {
    if (hubEvent.getName().equals(InitializationStatus.SUCCEEDED.toString())) {
        Log.i("AuthQuickstart", "Auth successfully initialized");
    } else if (hubEvent.getName().equals(InitializationStatus.FAILED.toString())) {
        Log.i("AuthQuickstart", "Auth failed to succeed");
    } else {
        switch (AuthChannelEventName.valueOf(hubEvent.getName())) {
            case SIGNED_IN:
                Log.i("AuthQuickstart", "Auth just became signed in.");
                break;
            case SIGNED_OUT:
                Log.i("AuthQuickstart", "Auth just became signed out.");
                break;
            case SESSION_EXPIRED:
                Log.i("AuthQuickstart", "Auth session just expired.");
                break;
            default:
                Log.w("AuthQuickstart", "Unhandled Auth Event: " + AuthChannelEventName.valueOf(hubEvent.getName()));
                break;
        }
    }
});

Solution

  • One way that I succeed to handle the problem is to pass the error lambda reference to errorAuthenticationHandle function as follows:

    Amplify.Auth.signIn(this.userName, password,
        result -> Log.i("AuthQuickstart", result.isSignInComplete() ?
            "Sign in succeeded" : "Sign in not complete"),
        this::errorAuthenticationHandle
    );
    
    private void errorAuthenticationHandle(AuthException error) {
        Log.e("AmplifyQuickstart", error.toString());
    
        switch (getErrorNumber(error)) {
            // Server require password reset
            case RESET:
                // Some code
                break;
    
            case FAILED:
                // Some code
                break;
        }
    }