小编ExN*_*ura的帖子

使用 StateFlow 对 Android ViewModel 进行单元测试,该 StateFlow 从另一个 StateFlow 映射最新版本,但永远不会触发 mapLatest

所以我有一个 ViewModel 我正在尝试进行单元测试。它使用 stateIn 运算符。我找到了有关如何测试使用 stateIn 运算符创建的状态流的文档https://developer.android.com/kotlin/flow/test但即使我正在收集流,mapLatest也永远不会触发。

\n
class DeviceConfigurationViewModel(\n    val systemDetails: SystemDetails,\n    val step: AddDeviceStep.ConfigureDeviceStep,\n    val service: DeviceRemoteService\n) : ViewModel(), DeviceConfigurationModel {\n\n    @OptIn(ExperimentalCoroutinesApi::class)\n    private val _state: StateFlow<DeviceConfigurationModel.State> =\n        service.state\n            .mapLatest { state ->\n                when (state) {\n                    DeviceRemoteService.State.Connecting -> {\n                        DeviceConfigurationModel.State.Connecting\n                    }\n                    is DeviceRemoteService.State.ConnectedState.Connected -> {\n                        state.sendCommand(step.toCommand(systemDetails))\n                        DeviceConfigurationModel.State.Connected\n                    }\n                    is DeviceRemoteService.State.ConnectedState.CommandSent -> {\n                        DeviceConfigurationModel.State.Configuring\n                    }\n                    is DeviceRemoteService.State.ConnectedState.MessageReceived -> {\n                        transformMessage(state)\n                    }\n                    is DeviceRemoteService.State.Disconnected -> {\n                        transformDisconnected(state)\n                    }\n                }\n            }\n            .distinctUntilChanged()\n            .stateIn(\n                viewModelScope,\n                SharingStarted.WhileSubscribed(5000), // Keep it alive for …
Run Code Online (Sandbox Code Playgroud)

android kotlin android-viewmodel kotlin-coroutines kotlin-flow

4
推荐指数
1
解决办法
1798
查看次数