如何在Koin的简化构造函数调用中传递数据
在Koin中用简化API传递构造函数自定义参数
针对你想简化get()调用同时传递testValue的需求,这里有几种可行的写法:
1. 复用同一依赖实例减少重复调用
如果多个依赖是同一类型(比如示例里的Application),先获取一次实例再复用就行:
val testModule = module { viewModelOf { val app = get<Application>() TestViewModel(app, app, app, testValue = true) } }
2. 用new()自动解析依赖+传自定义参数
要是想让Koin自动处理构造函数里的依赖,只手动传testValue,可以用new()的parameters参数:
val testModule = module { viewModel { new(::TestViewModel, parameters = { parametersOf(true) }) } }
注意:这种写法要求自定义参数放在构造函数最后,而且
parametersOf里的参数顺序要和构造函数里的自定义参数顺序对应上。
3. 命名参数+依赖注入混合写法
如果构造函数里的依赖是不同类型,用命名参数配合get(),代码会更清晰,也能避免位置参数搞混:
// 举个不同依赖的例子 class TestViewModel( dep1: RepositoryA, dep2: RepositoryB, dep3: ApiService, testValue: Boolean ) : ViewModel() // 模块定义 val testModule = module { viewModelOf { TestViewModel( dep1 = get(), dep2 = get(), dep3 = get(), testValue = true ) } }
内容的提问来源于stack exchange,提问作者koto
相关产品推荐
相关产品推荐

