I'm having issues injecting a scoped dependency in...
# koin
c
I'm having issues injecting a scoped dependency into my viewmodel and creating the viewmodel.
Copy code
class Cache(sess: SessionManager)

class MyViewModel(cache: Cache): ViewModel {}

module {
   single { SessionManager() }

   scope(named("userSession")) {
       scoped { Cache(get()) }

       viewModel { MyViewModel(get()) }
   }
} 

class MyFragment: Fragment() {
    private val myVm: MyViewModel by viewModel()
}
The above is the structure of my koin setup but when I run this it crashes my app with the error;
Caused by: org.koin.core.error.NoBeanDefFoundException: No definition found for class:'com.play.MyViewModel'. Check your definitions!
Please what could I be doing wrongly here?
a
private val myVm: MyViewModel by viewModel()
is requesting your viewModel from global space, but you defined it in a scope
you must query it from your userSession scope
in your Fragment you need to retrieve your scope:
val userSession : Scope by lazy { getKoin().getOrCreateScope( ... )}
and then, use
private val myVm: MyViewModel by userSession.viewModel()
c
Thanks! I tried this but then there are several parameters the
viewModel
method requires which I have no idea how to obtain. You have any example of this?
Ok, I was able to get the viewmodel with this;
Copy code
private val viewModel: MyViewModel by userScopeSession.viewModel(owner = { ViewModelOwner(viewModelStore) })
a
owner can be your fragment too
c
I think that has been changed.
a
🤔