Home > Enterprise >  LiveDataBuilder for one off events
LiveDataBuilder for one off events

Time:10-23

In the Android docs i found this article about conditional navigation where a login function returns LiveData to propagate the signIn result back from the viewmodel to the fragment. I assume the viewModel uses LiveDataBuilder to create the LiveData

//Fragment
fun login(username: String, password: String) {
    userViewModel.login(username, password).observe(viewLifecycleOwner, Observer { result ->
        if (result.success) {
            savedStateHandle.set(LOGIN_SUCCESSFUL, true)
            findNavController().popBackStack()
        } else {
            showErrorMessage()
        }
    })
}

I assume viewmodel does something like this.

fun login(username: String, password: String) = liveData {
   //perform login
}

I always thought this is bad practice since it creates a Livedata object on every login attempt. In this case i mostly use another SingleLiveData object to post the login result to. I also used callbacks quite often. Something like this:

fun login(username: String, password: String) {
    userViewModel.login(username, password, 
           onSuccess = {
              //DO SOMETHING
          }, one rror = {
              //DO SOMETHING
     })
}

Can someone explain which is now the best approach and what is the reason the other appraoches should not be used?

CodePudding user response:

You must not use callbacks in that way. You are leaking the views to the ViewModel.

LiveData used in this way is basically a glorified callback that will automatically be cancelled when the Fragment's view goes out of scope, so it's easier to use safely on the Fragment, and it avoids leaking the Fragment to the ViewModel. It saves you a lot of boilerplate that would be required to do it safely and without leaking the Fragmet.

I always thought this is bad practice since it creates a Livedata object on every login attempt.

I don't see what's bad about that. It's a lightweight object. Probably lighter weight than most of the Strings you work with in an app.

  • Related