如何使用匕首解决 ViewModel 中的 coroutineScope 依赖关系

Posted

技术标签:

【中文标题】如何使用匕首解决 ViewModel 中的 coroutineScope 依赖关系【英文标题】:How to resolve coroutineScope dependency in a ViewModel using dagger 【发布时间】:2021-11-03 03:12:43 【问题描述】:

我正在尝试将协程作用域注入到 viewModel,但我收到 dagger kotlinx.coroutines.CoroutineScope cannot be provided without an @Provides-annotated method. 的错误

Dagger 不知道如何在@Inject 中提供协程作用域

为此我添加了一个新的AppModule,带有一个getCoroutineScope函数,我应该如何在return语句中传递coroutineContext。

这是正确的方法吗?

关于我为什么要传递 coroutineScope 的上下文是为了更改在 unittest 中调度的内容。

错误信息

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()
        
    

新创建的 AppModule - 我稍后将包含在 dagger AppComponent 中

@Module
class AppModule 

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

提前致谢 回复

编辑

感谢 Karunesh 的意见

我的单元测试出现错误

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 供参考

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())
        
    

【问题讨论】:

【参考方案1】:

编写下面的代码来创建一个注释类并在你的 di 类中提供范围


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

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


    


如何实现:

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

【讨论】:

我试过了,我得到了和以前一样的错误我会根据你的回答用我所做的更新qn 我该如何使用我的单元测试 既然,我用刀柄一定是原因 代码运行良好,但我认为我在单元测试中做错了,让我将错误添加到问题中 我想我已经用单元测试实现更新了这个问题。我没有正确传递所需的调度程序。请问我该如何解决这个问题

以上是关于如何使用匕首解决 ViewModel 中的 coroutineScope 依赖关系的主要内容,如果未能解决你的问题,请参考以下文章

未解决的参考匕首 2 + kotlin + android gradle

如何使用 http 解决 VUE 中的 CORS 问题?

使用匕首 2 在 Kotlin 中的 AppWidgetProvider 中的字段注入

使用 Swagger UI 进行测试时如何解决 API 中的 CORS 错误(使用 Lumen 实现)

如何解决真实设备中的 CORS 问题?

如何使用 ASP.NET Core 解决 REACT 中的 CORS 错误