gpt4 book ai didi

android - Koin 的动态依赖注入(inject)是否可行

转载 作者:行者123 更新时间:2023-12-02 10:51:01 24 4
gpt4 key购买 nike

我正在研究当前 Android 应用程序中的 Koin 依赖注入(inject)库。

我有一个 CoroutineWorker 来完成我所有的后台工作。

我想做的是为我拥有的每种类型的后台工作动态注入(inject) lambda。

我有以下有效的代码,但它不是动态的

Koin模块:

const val BackgroundLambdaName: String = "back-ground-lambda"

val lambdaModule = module {

single(qualifier = named(BackgroundLambdaName)) {
background
}
}

private val background: suspend CoroutineScope.(Service) -> Unit = { service: Service ->
val limit: Int = 200
var offset: Int = 0

loop@ while (true) {

val networkResponse = service.move(options = mutableMapOf("limit" to limit, "offset" to offset))

if (networkResponse.next == null) {
break@loop
}
offset += limit
}
}

还有我的CoroutineWorker:

class BackgroundWorker(context: Context, params: WorkerParameters) : CoroutineWorker(context, params), KoinComponent {

private val service: Service by inject()
private val x_background: suspend CoroutineScope.(Service) -> Unit by inject(qualifier = named(BackgroundLambdaName))

override suspend fun doWork(): Result = coroutineScope {

withContext(Dispatchers.IO) {
downloadSynchronously(this)
Result.success()
}
}

private suspend fun downloadSynchronously(coroutineScope: CoroutineScope) {
x_background(coroutineScope, service)
}
}

有什么方法可以让我在运行时指定不同的 lambda 表达式以注入(inject)到我的 CoroutineWorker 中?

例如,如果我的 lambda Koin 模块定义了 10 个 lambda

BackgroundLambdaName_0 - BackgroundLambdaName_9

然后当开始我独特的后台工作时如下:

val constraints = Constraints.Builder()
.setRequiredNetworkType(NetworkType.CONNECTED)
.setRequiresBatteryNotLow(true)
.setRequiresCharging(true)
.build()

val backgroundWorkRequest = OneTimeWorkRequestBuilder<BackgroundWorker>()
.setConstraints(constraints)
.setBackoffCriteria(
BackoffPolicy.EXPONENTIAL,
OneTimeWorkRequest.MIN_BACKOFF_MILLIS,
TimeUnit.MILLISECONDS
).build()

// DYNAMICALLY set qualifier = named(BackgroundLambdaName) to one of
// BackgroundLambdaName_0 - BackgroundLambdaName_9

WorkManager.getInstance(application).enqueueUniqueWork(UNIQUE_WORK_NAME, ExistingWorkPolicy.KEEP, backgroundWorkRequest)

最佳答案

是的,Koin 2 是可能的,至少是完全可能的。

我猜你需要的第一个创建模块是“lambdaModule”

val coffeeAppModule = module {
single { CoffeeMaker(get(), get()) }
single<Pump> { Thermosiphon(get()) }
single<Heater> { ElectricHeater() }
}

然后动态加载模块并在不再需要时卸载。

    // after start
loadKoinModules(coffeeAppModule)

// resolve CoffeeMaker
get()<CoffeeMaker>

// drop module's definitions & instances when you don't need it anymore
unloadKoinModules(coffeeAppModule)

请引用库的维护者在这里您可以找到更多信息 https://medium.com/koin-developers/ready-for-koin-2-0-2722ab59cac3

关于android - Koin 的动态依赖注入(inject)是否可行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59105382/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com