I understand how to use ViewModel, Repositories and Room for transfer data from database to screen. But how implement login activity with POST method. Do I need create LiveData isAuthorized from ViewModel or AuthorizationRepository? Can anyone show example about using command methods with android architecture components?
This can be your login class, maybe extending ViewModel, so it keeps alive on configuration changes:
class LoginClass
{
var loginEvent = SingleLiveEvent<LoginEvent>()
fun startLogin(user: String, password: String)
{
loginEvent.value= LoginEvent(LoginStatus.LoginStart,null,null)
launch(UI) {
try{
bg{
//do login process
}.await()
loginEvent.value= LoginEvent(LoginStatus.LoginOk,null,null)
}
catch (error: Exception){
loginEvent.value= LoginEvent(LoginStatus.LoginFailed,error.message,null)
}
}
}
data class LoginEvent(var loginStatus: LoginStatus, var errorMessage: String?, var loginExtraData: Any?)
enum class LoginStatus
{
LoginStart,
LoginOk,
LoginFailed
}
}
You can observe the login status to react and change your UI accordingly:
val myLoginClass = LoginClass()
myLoginClass.loginEvent.observe(this@LifecycleOwner, Observer {
if(it==null)
return@Observer
when(it.loginStatus)
{
LoginClass.LoginStatus.LoginStart -> {
//show indeterinate progress bar, disable inputs, etc
}
LoginClass.LoginStatus.LoginOk -> {
//go to logged in activity
}
LoginClass.LoginStatus.LoginFailed -> {
//show login failed toast, hide progress bar, enable input, etc
}
}
})
To start login simply call the login method of your class:
loginButton.onClick {
myLoginClass.startLogin("user", "password")
}
Logically, you will need more than this, but you can use it as a skeleton.
SingleLiveEvent can be found here: https://github.com/googlesamples/android-architecture/blob/dev-todo-mvvm-live/todoapp/app/src/main/java/com/example/android/architecture/blueprints/todoapp/SingleLiveEvent.java
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With