I want to make an login activity based the "official" MVVM, Repository model.
I have looked at the Android Studio "Login" template and somewhat understood how that works. The flow chart below shows how I plan the data flow between classes. The template did not include the WebService part, instead the token was immediately return without a callback.
Since creating references (in callbacks) to the VM/Activity is bad practice, what are the options for having the token propagated back to the VM (represented by the dashed arrows)?
Notes:
Thanks
You don't need to create a LiveData
inside the repository. Instead, you can make a call from the VM to the repository.login(u,p)
and wait for the results to arrive. Once the results has arrived, just update the LiveData
instance inside the VM.
The network call must be done asynchronously anyway, or you can make use of the callback mechanism from the networking libraries like Retrofit.
Your ViewModel
will look like this (pseudo code):
class LoginViewModel: ViewModel{
LiveData<Result> login(String username, String password){
LiveData<Result> resultLiveData = new MutableLiveData<Result>();
// Let it be an async. call from Retrofit
Repository.login(username, password, new Callback<Result>{
void onResult(Result result){
resultLiveData.value = result // update the livedata.
}
}
return resultLiveData;
}
}