Koin sharing instances between modules

泪湿孤枕 提交于 2020-01-23 18:17:48

问题


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()) }    
        }
    }

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?


回答1:


  • 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()) }  
    
      }
    }
    
  • 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>()
    
  • And In onDestroy method

    commonScope.close()
    

    For more detail check koin documentation (8th point)



来源:https://stackoverflow.com/questions/56721048/koin-sharing-instances-between-modules

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!