Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Injecting CoroutineWorker using Hilt

I am trying to inject a coroutine worker using dagger hilt, I 've followed all the instructions in the documentation

https://developer.android.com/training/dependency-injection/hilt-jetpack which was intended for "Worker" not "coroutine Worker"..

but it gives an error :

java.lang.NoSuchMethodError: No interface method getBackgroundExecutor()Ljava/util/concurrent/Executor

..the same question was posted on stackoverflow with an answer that doesn't suit my case

Can not inject workmanager constructor with Hilt

here's the code and the error

I would be grateful if anyone can help...here's my code

package com.example.moviemania.work

import android.content.Context
import androidx.hilt.Assisted
import androidx.hilt.work.WorkerInject
import androidx.work.CoroutineWorker
import androidx.work.WorkerParameters
import com.example.moviemania.repository.MainRepository
import retrofit2.HttpException

class RefreshDataWorker @WorkerInject constructor (
    @Assisted appContext: Context,
    @Assisted params: WorkerParameters,
    val mainRepository: MainRepository
    ) : CoroutineWorker(appContext,params) {

    companion object {
        const val WORK_NAME = "com.example.moviemania.work.RefreshDataWorker"
    }

    override suspend fun doWork(): Result {
        try {
            mainRepository.refreshMovies()
        }catch (e: HttpException){
            return Result.retry()
        }
        return Result.success()
    }
}

@HiltAndroidApp
class MoviesApp : Application(), Configuration.Provider {
    @Inject lateinit var workerFactory: HiltWorkerFactory

    private val applicationScope = CoroutineScope(Dispatchers.Default)
    override fun getWorkManagerConfiguration() =
        Configuration.Builder()
            .setWorkerFactory(workerFactory)
            .setMinimumLoggingLevel(android.util.Log.DEBUG)
            .build()


    override fun onCreate() {
        super.onCreate()
        delayedInit()
    }

    private fun delayedInit() {
        applicationScope.launch {
            setupRecurringWork()
        }
    }
    private fun setupRecurringWork(){
        val repeatingRequest = PeriodicWorkRequestBuilder<RefreshDataWorker>(1,TimeUnit.DAYS).build()
        WorkManager.getInstance(applicationContext).enqueueUniquePeriodicWork(
            RefreshDataWorker.WORK_NAME,
            ExistingPeriodicWorkPolicy.KEEP,
            repeatingRequest
        )
    }
}

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    package="com.example.moviemania">

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <application
        android:name=".MoviesApp"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.MovieMania">
        <activity android:name=".ui.MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <provider
            android:name="androidx.work.impl.WorkManagerInitializer"
            android:authorities="com.example.moviemania.workmanager-init"
            tools:node="remove" />
    </application>

</manifest>

and here's the error

2021-01-11 09:23:44.685 29929-29960/com.example.moviemania E/AndroidRuntime: FATAL EXCEPTION: pool-2-thread-1
    Process: com.example.moviemania, PID: 29929
    java.lang.NoSuchMethodError: No interface method getBackgroundExecutor()Ljava/util/concurrent/Executor; in class Landroidx/work/impl/utils/taskexecutor/TaskExecutor; or its super classes (declaration of 'androidx.work.impl.utils.taskexecutor.TaskExecutor' appears in /data/app/com.example.moviemania-6m_-4lzXG2Ud-HIb1asUiQ==/base.apk)
        at androidx.work.CoroutineWorker.<init>(CoroutineWorker.kt:52)
        at com.example.moviemania.work.RefreshDataWorker.<init>(RefreshDataWorker.kt:22)
        at com.example.moviemania.work.RefreshDataWorker_AssistedFactory.create(RefreshDataWorker_AssistedFactory.java:25)
        at com.example.moviemania.work.RefreshDataWorker_AssistedFactory.create(RefreshDataWorker_AssistedFactory.java:13)
        at androidx.hilt.work.HiltWorkerFactory.createWorker(HiltWorkerFactory.java:55)
        at androidx.work.WorkerFactory.createWorkerWithDefaultFallback(WorkerFactory.java:83)
        at androidx.work.impl.WorkerWrapper.runWorker(WorkerWrapper.java:242)
        at androidx.work.impl.WorkerWrapper.run(WorkerWrapper.java:136)
        at androidx.work.impl.utils.SerialExecutor$Task.run(SerialExecutor.java:91)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1162)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:636)
        at java.lang.Thread.run(Thread.java:764)
like image 694
Mina Isaac Avatar asked Jan 11 '21 07:01

Mina Isaac


People also ask

How do you inject ViewModels with hilt?

Inject ViewModel objects with HiltProvide a ViewModel by annotating it with @HiltViewModel and using the @Inject annotation in the ViewModel object's constructor. Note: To use Dagger's assisted injection with ViewModels, see the following Github issue.

What is Hilt dependency injection?

Hilt provides a standard way to incorporate Dagger dependency injection into an Android application. The goals of Hilt are: To simplify Dagger-related infrastructure for Android apps. To create a standard set of components and scopes to ease setup, readability/understanding, and code sharing between apps.

What is HiltViewModel?

Annotation Type HiltViewModelIdentifies a ViewModel for construction injection. The ViewModel annotated with HiltViewModel will be available for creation by the dagger. hilt. android. lifecycle.

What is Hilt Kotlin?

Hilt is a new dependency injection library built on top of Dagger that simplifies its use in Android apps. This guide showcases the core functionality with a few code snippets to help you get started with using Hilt in your project.


Video Answer


2 Answers

I think it's an incorrect import statement: Here are the snippets

Please check your Hilt Modules for bad imports.

PS: I've included imports for you

AndroidManifest.xml

    <application
    ...
        <provider
            android:name="androidx.work.impl.WorkManagerInitializer"
            android:authorities="${applicationId}.workmanager-init"
            tools:node="remove" />
    </application>

MyApplication.kt

import android.app.Application
import androidx.hilt.work.HiltWorkerFactory
import androidx.work.Configuration
import androidx.work.ExistingPeriodicWorkPolicy
import androidx.work.PeriodicWorkRequestBuilder
import androidx.work.WorkManager
import dagger.hilt.android.HiltAndroidApp
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import java.util.concurrent.TimeUnit
import javax.inject.Inject

@HiltAndroidApp
class MyApplication : Application(), Configuration.Provider {
    @Inject
    lateinit var workerFactory: HiltWorkerFactory

    private val applicationScope = CoroutineScope(Dispatchers.Default)

    override fun getWorkManagerConfiguration() =
        Configuration.Builder()
            .setWorkerFactory(workerFactory)
            .setMinimumLoggingLevel(android.util.Log.DEBUG)
            .build()


    override fun onCreate() {
        super.onCreate()
        delayedInit()
    }

    private fun delayedInit() {
        applicationScope.launch {
            setupRecurringWork()
        }
    }

    private fun setupRecurringWork(){
        val repeatingRequest = PeriodicWorkRequestBuilder<RefreshDataWorker>(1, TimeUnit.DAYS).build()

        WorkManager.getInstance(applicationContext).enqueueUniquePeriodicWork(
            RefreshDataWorker.WORK_NAME,
            ExistingPeriodicWorkPolicy.KEEP,
            repeatingRequest
        )
    }
}

RefreshDataWorker.kt

import android.content.Context
import androidx.hilt.Assisted
import androidx.hilt.work.WorkerInject
import androidx.work.CoroutineWorker
import androidx.work.WorkerParameters
import java.lang.Exception

class RefreshDataWorker @WorkerInject constructor (
    @Assisted appContext: Context,
    @Assisted params: WorkerParameters,
    private val mainRepository: MainRepository
    ) : CoroutineWorker(appContext,params) {

    companion object {
        const val WORK_NAME = "com.example.moviemania.work.RefreshDataWorker"
    }

    override suspend fun doWork(): Result {
        try {
            mainRepository.refreshMovies()
        }catch (e: Exception){
            return Result.retry()
        }
        return Result.success()
    }
}

MainRepository.kt

import android.util.Log
import javax.inject.Inject

class MainRepository @Inject constructor() {
    fun refreshMovies() {
        Log.d("ManoO", "Hello first time from worker: initiated immediately")
    }
}

Gradle Scripts

Project
buildscript {
    ...

    dependencies {
        ...
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.4.21"
        classpath 'com.google.dagger:hilt-android-gradle-plugin:2.30.1-alpha'
    }
}

App

dependencies {
    ....

    implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:1.4.2"
    implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:1.4.2"

    implementation "com.google.dagger:hilt-android:2.30.1-alpha"
    kapt "com.google.dagger:hilt-android-compiler:2.30.1-alpha"
    implementation 'androidx.hilt:hilt-work:1.0.0-alpha02'
    kapt 'androidx.hilt:hilt-compiler:1.0.0-alpha02'

    def work_version = "2.5.0-beta02"
    implementation "androidx.work:work-runtime-ktx:$work_version"

}
like image 114
abd3lraouf Avatar answered Oct 14 '22 07:10

abd3lraouf


Since work version 2.6 it works using below androidmanifest.xml

AndroidManifest.xml

<provider
     android:name="androidx.startup.InitializationProvider"
     android:authorities="${applicationId}.androidx-startup"
     tools:node="remove">
</provider>

and in case of Worker class some annotation was changed. @HiltWorker , @AssistedInject

@HiltWorker
class RefreshWorker @AssistedInject constructor(
    @Assisted appContext: Context,
    @Assisted workerParams: WorkerParameters,
    val myRepository: MyRepository
) : CoroutineWorker(appContext, workerParams) {

    override suspend fun doWork(): Result {
        return Result.success()
    }

}

Developer site ( worker api ) https://developer.android.com/jetpack/androidx/releases/hilt

Replace @WorkerInject with @HiltWorker. @HiltWorker is now a type annotation and requires the usage of @AssistedInject in the constructor. (Ic2f15)

Developer site ( remove default worker initializer ) https://developer.android.com/topic/libraries/architecture/workmanager/advanced/custom-configuration#remove-default

remove the default initializer To provide your own configuration, you must first remove the default initializer. To do so, update AndroidManifest.xml using the merge rule tools:node="remove".

Since WorkManager 2.6, App Startup is used internally within WorkManager. To provide a custom initializer you need to remove the androidx.startup node.

like image 45
Hyoung ju kwon Avatar answered Oct 14 '22 07:10

Hyoung ju kwon