How to access a repository from a Worker created by a Broadcast Receiver?


I have a repository I create in the onCreate method of my application class. I also have a manifest-declared Broadcast Receiver which creates a Coroutine Worker which I would like to call a method from the repository. How can I access the instance created by the application? I have the applicationContext in the worker, but I can't figure out how to access properties of the application through it.

CheckInApplication.kt

class CheckInApplication : Application() { lateinit var container: AppContainer override fun onCreate() { super.onCreate() container = DefaultAppContainer(applicationContext) } }

Worker.kt

class CheckInWorker(ctx: Context, params: WorkerParameters) : CoroutineWorker(ctx, params) {

    val TAG = "CHECK_IN_WORKER"

    override suspend fun doWork(): Result {
        return try {

            //application.container.repository.fun()

            Log.d(TAG, "Work Success")
            Result.success()
        } catch (throwable: Throwable) {
            Log.e(TAG, "Work failure", throwable)
            Result.failure()
        }
    }
}
3
Mar 22 at 6:17 PM
User Avataruser32522523
#android#kotlin#broadcastreceiver#android-context#android-workmanager

Accepted Answer

In CheckInWorker, ctx is a Context. Given a Context, you can get the Application singleton via getApplicationContext():

val application = ctx.applicationContext as CheckInApplication
User AvatarCommonsWare
Mar 22 at 6:25 PM
1