Last active
July 13, 2019 13:16
-
-
Save AlonsoFloo/7c0b12e77c17d3284cd698052f014122 to your computer and use it in GitHub Desktop.
Kotlin tools for WorkManager Dagger injection
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
interface HasWorkerInjector { | |
fun workerInjector(): AndroidInjector<Worker> | |
} | |
class AndroidInjection { | |
companion object {} | |
} | |
fun AndroidInjection.Companion.inject(worker: Worker) { | |
val application = worker.applicationContext | |
if (application !is HasWorkerInjector) { | |
throw RuntimeException( | |
String.format( | |
"%s does not implement %s", | |
application.javaClass.canonicalName, | |
lu.neopixl.menj.dagger.worker.HasWorkerInjector::class.java.canonicalName | |
) | |
) | |
} | |
val workerInjector = application.workerInjector() | |
workerInjector.inject(worker) | |
} | |
abstract class DaggerWorker ( | |
appContext: Context, | |
workerParams: WorkerParameters | |
) : Worker(appContext, workerParams) { | |
init { | |
AndroidInjection.inject(this) | |
} | |
} | |
@Module | |
abstract class AndroidWorkerInjectionModule { | |
@Multibinds | |
internal abstract fun workerInjectorFactories(): Map<Class<out Worker>, AndroidInjector.Factory<out Worker>> | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@Module | |
internal abstract class MyWorkerDaggerModule { | |
@ContributesAndroidInjector(modules = []) | |
abstract fun worker(): MyWorker | |
} | |
class MyWorker( | |
appContext: Context, | |
workerParams: WorkerParameters | |
) : DaggerWorker(appContext, workerParams) { | |
@Inject | |
lateinit var objectToInject: String | |
override fun doWork(): Result { | |
// Code ... | |
return Result.success() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment