BRDroid
BRDroid

Reputation: 4388

How to resolve coroutineScope dependency in a ViewModel using dagger

I am trying to inject coroutine scope in to viewModel, but I get an error with dagger kotlinx.coroutines.CoroutineScope cannot be provided without an @Provides-annotated method.

Dagger does not know how to provide the coroutine scope in @Inject

For this I have added a new AppModule with a function getCoroutineScope, how should I pass the coroutineContext in the return statement.

Is this even the correct aproach?

Context on why I am passing coroutineScope is to change the dispatched in unittest.

Error message

example/breakingbad/di/AppComponent.java:8: error: [Dagger/MissingBinding] kotlinx.coroutines.CoroutineScope cannot be provided without an @Provides-annotated method.
public abstract interface AppComponent {
                ^
      kotlinx.coroutines.CoroutineScope is injected at
          com.example.breakingbad.viewModel.MainActivityViewModel(coroutineScopeProvider, …)
      com.example.breakingbad.viewModel.MainActivityViewModel is injected at
          com.example.breakingbad.CharactersFragment.viewModel
      com.example.breakingbad.CharactersFragment is injected at
          com.example.breakingbad.di.AppComponent.inject(com.example.breakingbad.CharactersFragment)

MainActivityViewModel

class MainActivityViewModel @Inject constructor(
        private val coroutineScopeProvider: CoroutineScope? = null,
    private val dataRepository: DataRepository
): ViewModel() {
    val _charactersLiveData = MutableLiveData<Result<ArrayList<Character>>>()
    val charactersLiveData: LiveData<Result<ArrayList<Character>>> = _charactersLiveData

    private val coroutineScope = getViewModelScope(coroutineScopeProvider)

    fun fetchCharacters() {
        coroutineScope.launch {
            _charactersLiveData.value = dataRepository.getCharacters()
        }
    }
}

Newly created AppModule - which I will later include in the dagger AppComponent

@Module
class AppModule {

    @Provides
    fun getCoroutineScope(): CoroutineScope {
        return CoroutineScope()
    }
}

Thanks in advance R

Edit

Thank you Karunesh for your input

I am getting an error in my unit test

java.lang.NullPointerException
    at kotlinx.coroutines.CoroutineContextKt.newCoroutineContext(CoroutineContext.kt:33)
    at kotlinx.coroutines.BuildersKt__Builders_commonKt.launch(Builders.common.kt:52)
    at kotlinx.coroutines.BuildersKt.launch(Unknown Source)
    at kotlinx.coroutines.BuildersKt__Builders_commonKt.launch$default(Builders.common.kt:47)
    at kotlinx.coroutines.BuildersKt.launch$default(Unknown Source)
    at com.example.breakingbad.MainActivityViewModelTest.fetchCharacters(MainActivityViewModelTest.kt:60)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:59)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:56)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306)
    at org.junit.runners.BlockJUnit4ClassRunner$1.evaluate(BlockJUnit4ClassRunner.java:100)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:366)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:103)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:63)
    at org.junit.runners.ParentRunner$4.run(ParentRunner.java:331)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:79)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:329)
    at org.junit.runners.ParentRunner.access$100(ParentRunner.java:66)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:293)
    at org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:413)
    at org.mockito.internal.runners.DefaultInternalRunner$1.run(DefaultInternalRunner.java:79)
    at org.mockito.internal.runners.DefaultInternalRunner.run(DefaultInternalRunner.java:85)
    at org.mockito.internal.runners.StrictRunner.run(StrictRunner.java:39)
    at org.mockito.junit.MockitoJUnitRunner.run(MockitoJUnitRunner.java:163)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
    at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:33)
    at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:230)
    at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:58)

MainActivityViewModelTest

@RunWith(MockitoJUnitRunner::class)
class MainActivityViewModelTest {


    @Mock
    private lateinit var dataRepository: DataRepository

    @Mock
    private lateinit var applicationScope: CoroutineScope

    @Mock
    private lateinit var dataObserver: Observer<Result<List<Character>>>

    @InjectMocks
    private lateinit var mainActivityViewModel: MainActivityViewModel


    @Test
    fun fetchCharacters() {
        applicationScope.launch(Dispatchers.IO) {
            Mockito.`when`(dataRepository.getCharacters())
                    .thenReturn(Result.success(arrayListOf(Character(
                            name = "myName",
                            img = "image",
                            occupation = arrayListOf(),
                            status = "status",
                            nickname = "nickName",
                            appearance = arrayListOf()
                    ))))
            mainActivityViewModel.fetchCharacters()
            verify(dataRepository).getCharacters()

            Mockito.verify(dataObserver).onChanged(Result.success(listOf(Character (
                    name = "myName",
                    img = "image",
                    occupation = arrayListOf(),
                    status = "status",
                    nickname = "nickName",
                    appearance = arrayListOf()
            ))))
            mainActivityViewModel.charactersLiveData.removeObserver(dataObserver)
        }
    }

MainActivityViewModel for reference

class MainActivityViewModel @Inject constructor(
        @ApplicationScope private val applicationScope: CoroutineScope,
        private val dataRepository: DataRepository
): ViewModel() {
    val _charactersLiveData = MutableLiveData<Result<ArrayList<Character>>>()
    val charactersLiveData: LiveData<Result<ArrayList<Character>>> = _charactersLiveData


    fun fetchCharacters() {

        applicationScope.launch(Dispatchers.IO) {
            //_charactersLiveData.value = dataRepository.getCharacters()
            _charactersLiveData.postValue(dataRepository.getCharacters())
        }
    }
}

Upvotes: 1

Views: 2292

Answers (1)

Karunesh Palekar
Karunesh Palekar

Reputation: 2345

Write the below code which creates an annotation class and provides the scope in your di class


@Retention(AnnotationRetention.BINARY)
@Qualifier
annotation class ApplicationScope

@ApplicationScope
@Provides
@Singleton
fun providesApplicationScope() = CoroutineScope(SupervisorJob())


    


How to Implement :

class WhereCoroutineIsToBeInjected(
  @ApplicationScope private val applicationScope: CoroutineScope
){
  applicationScope.launch(Dispatchers.IO){
}

Upvotes: 3

Related Questions