jeudi 24 décembre 2020

How to design login viewmodel in android

I am building an android app by using compose, and I am stuck at how to write logic for my login button.

When that btn is clicked, I need first send request to the server with username and password wait for the response which contains code indicates if the username and password are correct. If the input is valid then I need to start the MainActivity with some data in response.

There are two approaches I think can work:

  • observe the databean livedata in viewmodel and determine if need to start MainActivity when livedata update(which indicates button been pressed and request been made). But I think this donot meets the design idea(click event->network request->start activity or not).
class LoginActivity : AppCompatActivity() {
    private val loginViewModel by viewModels<LoginViewModel>()

    override fun onCreate(savedInstanceState: Bundle?) {
        ...
        loginViewModel.loginBean.observe(this) {
            if (it?.code == 200) {
                startActivity(Intent(this, MainActivity::class.java))
            }
        }
    }
}

@Composable
fun LoginScreen(viewModel: LoginViewModel) {
    val context = AmbientContext.current
    Scaffold(
        topBar = { TopAppBar(title = { Text("LOGIN") }) }
    ) {
        LoginScreenContent(loginAction = { username, password ->
            viewModel.login(username, password)
        })
    }
}
  • pass the callback when invoke viewmodel login function and invoke the callback in network request. But this may cause memory leak because network request doesn't respect the lifecycle.
@Composable
fun LoginScreen(viewModel: LoginViewModel) {
    val context = AmbientContext.current
    Scaffold(
        topBar = { TopAppBar(title = { Text("LOGIN") }) }
    ) {
        LoginScreenContent(loginAction = { username, password ->
            viewModel.login(username, password){
                if (it?.code == 200) {
                    startActivity(Intent(context as LifeCycleOwner, MainActivity::class.java))
                }
            }
        })
    }
}

So which approach I should take or if there are some better way to do it.

Aucun commentaire:

Enregistrer un commentaire