Koin在模块之间共享实例 [英] Koin sharing instances between modules

查看:479
本文介绍了Koin在模块之间共享实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将Koin库用于一个Android项目. 我想在模块之间共享一些实例,因为在整个应用程序中它们经常被使用. 例如:

I'm using the Koin library for an Android project. I want to share some instances between modules since they are used a lot throughout the application. For instance:

val moduleA = module {
    scope(named<FragmentA>()) {
        scoped { FirebaseFirestore.getInstance() }

        scoped { LocalDatabase.getInstance(App.sContext) }
        scoped { NetworkDataSourceA(get()) }    
    }
}

val moduleB = module {
        scope(named<FragmentB>()) {
            scoped { FirebaseFirestore.getInstance() }

            scoped { LocalDatabase.getInstance(App.sContext) }
            scoped { NetworkDataSourceB(get()) }    
        }
    }

从以下模块中可以看到,两个模块之间的FirebaseFirestore.getInstance()LocalDatabase.getInstance(App.sContext)相同. 有没有一种方法可以让我声明包含FirebaseFirestore.getInstance()LocalDatabase.getInstance(App.sContext)moduleC,然后在moduleAmoduleB上调用它?

As we can see from the following modules the FirebaseFirestore.getInstance() and the LocalDatabase.getInstance(App.sContext) are the same between both modules. Is there a way where I can declare lets say a moduleC that contains FirebaseFirestore.getInstance() and the LocalDatabase.getInstance(App.sContext) and then call it on the moduleA and moduleB?

推荐答案

  • 您可以通过创建范围来做到这一点.虽然我没有尝试.

    • You can do this by creating scope. Though I didn't tried.

      val moduleA = module {
      scope(named("CommonScope")) {
      
      scoped { FirebaseFirestore.getInstance() }
      scoped { LocalDatabase.getInstance(App.sContext) }
      
      scoped { NetworkDataSourceA(get()) }   
      scoped { NetworkDataSourceB(get()) }  
      
        }
      }
      

    • 现在,使用下面的代码行在FragmentA中创建作用域.( 也与用于NetworkDataSourceB的FragmentB相同)

    • Now, create your scope in your FragmentA using below line.( also same for FragmentB for NetworkDataSourceB)

      private val commonScope = getKoin().getOrCreateScope("scope1",named("CommonScope"))
      val networkDataSourceA = commonScope.get<NetworkDataSourceA>()
      

    • 并在onDestroy方法中

      commonScope.close()
      

      有关更多详细信息,请参见科恩文档(第8点)

      For more detail check koin documentation (8th point)

      这篇关于Koin在模块之间共享实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆