InsertKoinIO / koin

Koin - a pragmatic lightweight dependency injection framework for Kotlin & Kotlin Multiplatform
https://insert-koin.io
Apache License 2.0
9.03k stars 715 forks source link

by viewModel() gives compilation error #221

Closed johnfrey99 closed 6 years ago

johnfrey99 commented 6 years ago

Describe the bug

getting compilation error: Expression 'viewModel' of type 'PatientViewModel' cannot be invoked as a function. The function 'invoke()' is not found

Koin project used and used version (please complete the following information):

koin-androidx-viewmodel version 1.0.0-RC-1

module definition

val appModule = module {
    viewModel { PatientViewModel(get()) }
  ....
}

fragment definition

class PatientFragment : Fragment()
{
    val viewModel: PatientViewModel by viewModel()
...
}

viewModel definition

import androidx.lifecycle.LiveData
import androidx.lifecycle.MediatorLiveData
import androidx.lifecycle.ViewModel

class PatientViewModel(val patientRepo: PatientRepository) : ViewModel() {
    private val patient = MediatorLiveData<Patient>()
...
johnfrey99 commented 6 years ago

fixed with private val viewModel by viewModel<PatientViewModel>()

markkko commented 5 years ago

fixed with private val viewModel by viewModel<PatientViewModel>()

I am getting Unresolve reference: viewModel with that

aiueoH commented 5 years ago

fixed with private val viewModel by viewModel<PatientViewModel>()

I am getting Unresolve reference: viewModel with that

Try import this

import org.koin.android.viewmodel.ext.android.viewModel

gligerglg commented 5 years ago

Inside the fragment use 'by sharedViewModel()' instead of 'by viewModel()'

MarcelReiter commented 4 years ago

fixed with private val viewModel by viewModel<PatientViewModel>()

I am getting Unresolve reference: viewModel with that

Try import this

import org.koin.android.viewmodel.ext.android.viewModel

AndroidX users having the same problem can just use import org.koin.androidx.viewmodel.ext.android.viewModel

(Notice the bold x)

atcarlso commented 2 years ago

In case anyone else gets this error:

Ugh. I was having this error ("Expression 'viewModel' of type 'MyCoolViewModel' cannot be invoked as a function") and couldn't figure it out, until I was playing around and found it was due to having a parameter in my Composable function also named 'viewModel' and that must've been conflicting with the built-in 'viewModel' Composable. I changed my other variable name to just 'vm' and then was able to import 'androidx.lifecycle.viewmodel.compose.viewModel' and that fixed my issue.

The error was happening here: @Composable fun FirearmsScreen( navController: NavController, vm: FirearmsViewModel = viewModel() <---- error until I changed this variable name from 'viewModel' to 'vm' ) {