Search code examples
androidkotlinfirebase-authenticationviewmodel

initialize value in android viewmodels


I got an error when using init method in viewmodels and access it at the main activity.

Unresolved reference: loginStatus

I think it cannot access this value.

how can I solve this?

class LoginViewModel: ViewModel() {

    init {
        if (Firebase.auth.currentUser != null) {
            val loginStatus by mutableStateOf(true)

        } else {
            val loginStatus by mutableStateOf(false)
        }
    }
}

@AndroidEntryPoint
class MainActivity() : AppCompatActivity() {

    private val loginViewModel: LoginViewModelby viewModels()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        if (loginViewModel.loginStatus) {
            println("login true")
        }
    }
}

and I tried to solve this problem using lazy method, however, it didn't work. Is there any method?

val loginStatus : Boolean by lazy { mutableStateOf(true)}

Solution

  • You can write the code outside the init block like this

    val loginStatus by lazy {
          mutableStateOf(Firebase.auth.currentUser != null)    
      }
    
    or 
    
     val loginStatus by lazy {
            if (Firebase.auth.currentUser != null) {
                mutableStateOf(true)
    
            } else {
                mutableStateOf(false)
            }
        }