1

Hello developers in a composable function i can get context like this : LocalContext.current but how can i get it from a viewmodel class ???This is my viewmodel:

class LoginViewModel(
    private val _global: GlobalServices = GlobalServices(),
    private val _login:LoginModel= LoginModel(),
    private val _loginService: LoginService =LoginService(),
    private val retrofitService: IRetrofitService = RetrofitService(),
    private val storage:Storage= Storage()
):ViewModel() {
    
    val paddingMain=10.dp
    val isChecked = mutableStateOf(false)
    val disabled =  mutableStateOf(true)
    val iconSize=150.dp
    val signInFail= mutableStateOf(false)
    val showSuccess= mutableStateOf(false)

    val global=_global

    val login= mutableStateOf(_login, policy = neverEqualPolicy())//policiy is set for not create a copy of LoginModel when set state

    fun setEmail(email:String){
        login.value.correo=email
        refreshStateOfLogin()
    }
    fun setPassword(ppassword:String){
        login.value.password=ppassword
        refreshStateOfLogin()
    }
}
sofnomic cr
  • 132
  • 1
  • 9

2 Answers2

1

You should either have a context parameter for your ViewModel

class LoginViewModel(
    private val context: Context,
    private val _global: GlobalServices = GlobalServices(),
    private val _login:LoginModel= LoginModel(),
    private val _loginService: LoginService =LoginService(),
    private val retrofitService: IRetrofitService = RetrofitService(),
    private val storage:Storage= Storage()
):ViewModel(){

} 

or extend AndroidViewModel class and pass application.

class  LoginViewModel(application: Application) : AndroidViewModel(application){
    init{
        (application as Context)...
    }
}

AndroidViewModel vs ViewModel

Thracian
  • 43,021
  • 16
  • 133
  • 222
  • I don't think the AndroidViewModel is a good idea for the reasons explained in the link. Google is making things much more complicated than Apple and needlessly. A very cumbersome Kotlin language and strange things like these because if I use ViewModel, which in theory is correct, then it has that limitation, they don't even know what they are doing. – sofnomic cr Jul 15 '22 at 18:03
  • 1
    When i create my ViewModel or UseCase classes that require Android specific classes, assets, resources i prefer using dependency inversion and dependency injection. I pass these classes as interface and bind and inject them with dagger. that way they are easy to mock and ViewModels are unit testable – Thracian Jul 15 '22 at 18:10
0
class LoginViewModel @Inject constructor(
    @ApplicationContext context: Context,
    private val _global: GlobalServices = GlobalServices(),
    private val _login:LoginModel= LoginModel(),
    private val _loginService: LoginService =LoginService(),
    private val retrofitService: IRetrofitService = RetrofitService(),
    private val storage:Storage= Storage()
):ViewModel(){}
Cabezas
  • 9,329
  • 7
  • 67
  • 69