https://kotlinlang.org logo
#android-architecture
Title
# android-architecture
c

Can Korkmaz

02/06/2022, 6:24 PM
Can anyone check if I'm doing something wrong with instantiating a viewmodel? here is the code:
Copy code
@Preview
@Composable
fun LoginScreenPreview(){
    val navController = rememberNavController()
    val main: MainActivity = MainActivity()
    val myfactory = MainViewModelFactory(Database.getInstance(main.applicationContext).Dao, main.application)
    val viewModel: MainViewModel = viewModel(
        factory =myfactory
    )
    //TextField(value ="xxx", onValueChange ={} )
    LoginScreen(navController,  viewmodel = viewModel)
}
and viewmodel factory:
Copy code
class MainViewModelFactory(
    private val dataSource: Dao,
    private val application: Application
): ViewModelProvider.Factory{
    @Suppress("unchecked_cast")
    override fun <T : ViewModel> create(modelClass: Class<T>): T {
        if (modelClass.isAssignableFrom(MainViewModel::class.java)) {
            return MainViewModel(dataSource, application) as T
        }
        throw IllegalArgumentException("Unknown ViewModel class")
    }
}
The login screen only has basic fields such as textfields and a button, but uses data from viewmodel. Can't preview anything as of this state.
f

Francesc

02/06/2022, 6:32 PM
You can't instantiate an Activity by calling its constructor, you should not pass a navigation controller to your composables (pass a lambda), and you should be providing fakes for the dependencies (viewmodel)
👍 1
c

Can Korkmaz

02/06/2022, 6:37 PM
Thank you for answering. Why should I not pass the navController, isn't it more convenient this way? I'll learn about the last part, creating fakes for the dependencies.
f

Francesc

02/06/2022, 6:51 PM
It makes your previews and tests that much harder, it's best practice to pass a lambda, check this https://developer.android.com/jetpack/compose/navigation#testing
✔️ 1
c

Can Korkmaz

02/06/2022, 7:19 PM
So all of a sudden clean architecture makes sense, I've been struggling (failing) to get my viewmodels with repo or dao arguments to work in preview. Probably unrelated.
f

Francesc

02/06/2022, 8:08 PM
I have a sample project here that you may find useful for reference https://github.com/fvilarino/Weather-Sample/tree/feature/compose
👍 1
4 Views