Need help to refactor FIrebase phone authentication into MVVM architecture

Viewed 565

I am unable to figure out how to handle login Result from FirebaseLoginRepository class back to LoginViewModel after authentication like whether it's successful or not ,should i use a callback listener as we do in MVP pattern ?

Pardon me in case of misunderstanding or some unconventional issue as this is my first question on StackOverflow

I don't know i don't have the slightest idea and couldn't find anything useful over the internet

public void login{

        auth.signInWithCredential(credential).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
            @Override
            public void onComplete(@NonNull Task<AuthResult> task) {

                if(task.isSuccessful()){
                    //using login Result callback as unable to figure out how 
                    //to hand back result to LoginViewModel 
                   //i am certain that doing this breaks the principle of MVVM
                    loginResultCallback.onSuccess();
                }else {
                    loginResultCallback.onError();
                }
            }
        });

}
1 Answers

Assuming you are doing this on a background thread, you could do something like:

public void login{
        CountDownLatch latch = new CountDownLatch(1);
        auth.signInWithCredential(credential).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
            @Override
            public void onComplete(@NonNull Task<AuthResult> task) {

                if(task.isSuccessful()){
                    //using login Result callback as unable to figure out how 
                    //to hand back result to LoginViewModel 
                   //i am certain that doing this breaks the principle of MVVM
                   viewModel.something = something;
                }else {
                    loginResultCallback.onError();
                }
                latch.countDown();
            }
        });
        try {
          latch.await(30000);
        } catch (TimeoutException e) {
          Log.e("TUT", "Error timeed out", e);
        }
}

This allows you to block a thread and wait for a callback to happen, thus its a way to abstract a callback and use LiveData. You just have to be aware of what it is doing to the threads.

Outside of this you should look to see if the firebase API has a synchronous method for the same API.

https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/CountDownLatch.html

Related