Single instance of firebase - android

How to get single instance of firebase in android throughout application.
Iam getting instance from class.whlie trying to do from module level am getting fail.
Class firebasemodule{
Var module = module{
singlee(createdatstart=true){
gett<Firebase>().instance}}
}
In app level class
Startkoin{ module(listof(firebasemodule))}
Here am getting error.
Any suggestion accepted and I would be helpful for me and for many also.

You should use
class FirebaseModule {
val module = module {
single {
FirebaseFirestore.getInstance()
}
}
}

If don't want to take instance in this module , we can create seperate
class for firebase and call that class in module.
class FirebaseModule {
val module = module {
single {
FirebaseHandler()
}
}
}
class FirebaseHandler(){
val firebase = Firebase.getInstance()
}

Related

Koin dependency Injection Isssue - Android

In my android application am using MVVM architecture and using koin library for DI.
Below is my Repository class:
class JaiminRepository constructor(
private var remoteDataSource : RemoteDataSource,
private var enrollApiInterface : EnrollApiInterface
) {
...
}
Created module for is as below:
val jaiminRepositoryModule = module {
single {
JaiminRepository(get(),get())
}
}
For this I am getting error as :
Instance creation error : could not create instance for
[Singleton:'com.jaimin.sdk.repository.JaiminRepository']:
org.koin.core.error.NoBeanDefFoundException: |- No definition found
for class:'com.jaimin.api.RemoteDataSource'. Check your definitions!
org.koin.core.scope.Scope.throwDefinitionNotFound(Scope.kt:287)
org.koin.core.scope.Scope.resolveValue(Scope.kt:257)
So I have added factory for RemoteDataSource.
factory {
RemoteDataSource()
}
and finally it look like as below:
val jaiminRepositoryModule = module {
factory {
RemoteDataSource()
}
single {
JaiminRepository(get(),get())
}
}
But still am getting error. What might be the issue? Do I need to do something with EnrollApiInterface also? Please guide. Thanks in Advance.
You have to define all dependencies in the module(or another module), otherwise your repository can't be created. Make sure you also provide the EnrollApiInterface:
val jaiminRepositoryModule = module {
factory<EnrollApiInterface> {
EnrollApiInterfaceImpl()
}
factory {
RemoteDataSource()
}
single {
JaiminRepository(get(),get())
}
}

How to scope a Usecase to a Feature / Activity in Koin

I'm maintaining a large app (mostly) using a "one feature one activity"-architecture.
Now i'd like to scope a usecase, so it lives as long as the activity, something like this:
// koin module
scope<MyFeatureActivity> {
viewModel { MyFeatureActivityViewModel() }
viewModel { MyFeatureFragmentAViewModel(usecase = get()) }
viewModel { MyFeatureFragmentBViewModel(usecase = get()) }
scoped { MyFeatureUseCase() }
}
// fragments
class FeatureAFragment: AppCompatDialogFragment(){
private val viewModel by viewModel<MyFeatureFragmentAViewModel>()
....
}
// activity
class MyFeatureActivity : ScopeActivity() { ... }
However, this doesn't work. When launching MyFeatureFragmentA from MyFeatureActivity it's throwing an Exception:
org.koin.core.error.NoBeanDefFoundException:
|- No definition found for class:'MyFeatureAViewModel'. Check your definitions!
What am i doing wrong?
Please note: I would not like to just skip scopes and make the usecase a single (or a factory), since it actually stores some data relevant to only this activity: The data should be kept while we're in this feature, but dismissed when leaving it.

How to access an instance from one Kodein module in a different module?

When using Kodein, if I have 2 modules and module B needs to use an instance from module A, is the best practice to import module A into module B or is there a better way to do it?
For example, I have a networkingModule:
val networkingModule = Kodein.Module("networking") {
bind<Retrofit>() with singleton {
Retrofit.Builder()
.baseUrl("https://api.example.com/")
.build()
}
}
And subscribersModule needs the Retrofit instance from networkingModule:
val subscribersModule = Kodein.Module("subscribersModule") {
import(networkingModule)
bind<SubscribersService>() with singleton {
instance<Retrofit>().create(SubscribersService::class.java)
}
}
Is adding the import(networkingModule) in subscribersModule the best way to do it?
At the end, if your modules are used in one project, you're not force to make them dependant.
Instead you can import them in a global container, like this:
val applicationContainer = Kodein {
import(subscribersModule)
import(networkingModule)
// ...
}
Kodein-DI will solve the dependencies for you.

Koin Scope and Interface

I am using Koin di library in my project. Version of lib is 1.0.0-RC-1.
My module:
val appModule = module {
scope("UserScope") { UserToaster(androidContext()) as Toaster }
scope("AnonScope") { AnonToaster(androidContext()) as Toaster }
}
I started koin in my Application class and created scope:
override fun onCreate() {
super.onCreate()
startKoin(this, listOf(appModule))
getKoin().getOrCreateScope("AnonScope")
}
And next I tried to inject implementation of Toaster from current scope to variable in Activity. Here the code:
private val toaster: Toaster by inject(scope = "AnonScope")
After this I got an error:
Caused by: org.koin.error.DependencyResolutionException: Multiple definitions found for type 'interface com.example.nkirilov.playground.Toaster (Kotlin reflection is not available)' - Koin can't choose between :
Scope [name='UserScope',class='com.example.nkirilov.playground.Toaster']
Scope [name='AnonScope',class='com.example.nkirilov.playground.Toaster']
Check your modules definition, use inner modules visibility or definition names.
I do not understand why this does not work (If use single with different names - it will work). Is that koin bug? How to avoid this error?
I implemented it like this
Module:
val navigationModule = module {
scope(DI.APP_SCOPE) { ClassA().create }
scope(DI.APP_SCOPE) { get(scopeId = DI.APP_SCOPE).classB }
scope(DI.APP_SCOPE) { get(scopeId = DI.APP_SCOPE).classC }
}
val authModule = module {
scope(DI.AUTH_SCOPE) { ClassA.create(ChildClassB(get(scopeId = DI.APP_SCOPE))) }
scope(DI.AUTH_SCOPE) { get(scopeId = DI.AUTH_SCOPE).classB }
scope(DI.AUTH_SCOPE) { get(scopeId = DI.AUTH_SCOPE).classC }
}
Main Activity:
private val classC: ClassC by inject(scope = getKoin().getOrCreateScope(APP_SCOPE))
AuthActivity:
private val classC: ClassC by inject(scope = getKoin().getOrCreateScope(DI.AUTH_SCOPE))
your definitions have the same name in Koin. Current version (~1.0.*) avoid you to specify which scope to use, by automating resolving a type and it's session id.
Can you avoid describe your definitions with same type, like:
val appModule = module {
scope("UserScope") { UserToaster(androidContext()) }
scope("AnonScope") { AnonToaster(androidContext()) }
}
Else we would need a feature to specify which scope to use when resolving a type. You would resolve it with:
val userScope = getScope("UserScope")
get<Toaster>(scope = userScope)

How to provide parameters in Koin dry run test?

My ViewModel needs repository & genre through constructor. repository is provided by Koin & genre string is provided from activity
// Main app module
val MovieListModule: Module = applicationContext {
// provide repository
bean {
DummyMovieListRepository() as MovieListRepository
}
// provides ViewModel
viewModel { params: ParameterProvider ->
MovieListViewModel(respository = get(), genre = params["key.genre"])
}
}
//Module list for startKoin()
val appModules = listOf(MovieListModule)
//in activity
val viewModel = getViewModel<MovieListViewModel> {
mapOf("key.genre" to "Action / Drama")
}
// dry run test which fails
class KoinDryRunTest : KoinTest {
#Test
fun dependencyGraphDryRun() {
startKoin(list = appModules)
dryRun()
}
}
// some error log
org.koin.error.MissingParameterException: Parameter 'key.genre' is missing
at org.koin.dsl.context.ParameterHolder.get(ParameterHolder.kt:46)
org.koin.error.BeanInstanceCreationException: Can't create bean Factory[class=io.github.karadkar.popularmovies.MovieListViewModel, binds~(android.arch.lifecycle.ViewModel)] due to error :
org.koin.error.MissingParameterException: Parameter 'key.genre' is missing
here Koin (v 0.9.3) injection inactivity works as expected but the dry run test fails as it can't find parameter key.genre. Check full error-log
Is there any way to mock/provide key.genre value to dry run test?
full app source
as Arnaud Giuliani pointed on twitter. dryRun accepts lambda function for parameters
class KoinDryRunTest : KoinTest {
#Test
fun dependencyGraphDryRun() {
startKoin(list = appModules)
dryRun() {
mapOf("key.genre" to "dummy string")
}
}
}

Categories

Resources