ViewModel中的StateFlow和SharedFlow,使用建议以及单元测试(2)

img
img
img

既有适合小白学习的零基础资料,也有适合3年以上经验的小伙伴深入学习提升的进阶课程,涵盖了95%以上软件测试知识点,真正体系化!

由于文件比较多,这里只是将部分目录截图出来,全套包含大厂面经、学习笔记、源码讲义、实战项目、大纲路线、讲解视频,并且后续会持续更新

需要这份系统化的资料的朋友,可以戳这里获取

2.我需要重复发射和收集同样的值吗?
如果需要,那考虑SharedFlow,因为StateFlow会忽略连续两次重复的值。

3.当有新的订阅者订阅的时候,我需要发射最近的多个值吗?
如果需要,那考虑SharedFlow,可以配置replay参数。

compose中收集流的方式

关于在UI层收集ViewModel层的热流方式,官方文档已经有介绍,但是没有补充在JetPack Compose中的收集流方式,下面补充一下。

先添加依赖implementation 'androidx.lifecycle:lifecycle-runtime-compose:2.6.0-alpha03'

// 收集StateFlow
val uiState by viewModel.userFlow.collectAsStateWithLifecycle()

// 收集SharedFlow,区别在于需要赋初始值
val uiState by viewModel.userFlow.collectAsStateWithLifecycle(
    initialValue = UiState.Loading
)

when(uiState) {
    is UiState.Loading -> TODO()
    is UiState.Success -> TODO()
    is UiState.Error -> TODO()
}

使用collectAsStateWithLifecycle()也是可以保证流的收集操作之发生在应用位于前台的时候,避免造成资源浪费。

单元测试

由于我们会在ViewModel中使用到viewModelScope,首先可以定义一个MainDispatcherRule,用于设置MainDispatcher。

import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.test.TestDispatcher
import kotlinx.coroutines.test.UnconfinedTestDispatcher
import kotlinx.coroutines.test.resetMain
import kotlinx.coroutines.test.setMain
import org.junit.rules.TestRule
import org.junit.rules.TestWatcher
import org.junit.runner.Description

/**
 * A JUnit [TestRule] that sets the Main dispatcher to [testDispatcher]
 * for the duration of the test.
 */
class MainDispatcherRule(
  val testDispatcher: TestDispatcher = UnconfinedTestDispatcher()
) : TestWatcher() {
  override fun starting(description: Description) {
    super.starting(description)
    Dispatchers.setMain(testDispatcher)
  }

  override fun finished(description: Description) {
    super.finished(description)
    Dispatchers.resetMain()
  }
}

将MainDispatcherRule用于ViewModel单元测试代码中:

class MyViewModelTest {
  @get:Rule
  val mainDispatcherRule = MainDispatcherRule()

  ...
}

1.测试StateFlow

现在我们有一个业务ViewModel如下:

@HiltViewModel
class MyViewModel @Inject constructor(
  private val userRepository: UserRepository
) : ViewModel() {

  private val _userFlow = MutableStateFlow<UiState>(UiState.Loading)
  val userFlow: StateFlow<UiState> = _userFlow.asStateFlow()

  fun onRefresh() {
    viewModelScope.launch {
      userRepository
        .getUsers().asResult()
        .collect { result ->
          _userFlow.update {
            when (result) {
              is Result.Loading -> UiState.Loading
              is Result.Success -> UiState.Success(result.data)
              is Result.Error -> UiState.Error(result.exception)
            }
          }
        }
    }
  }
}

单元测试代码如下:

class MyViewModelTest{
    @get:Rule
    val mainDispatcherRule = MainDispatcherRule()

    // arrange
    private val repository = TestUserRepository()

    @OptIn(ExperimentalCoroutinesApi::class)
    @Test
    fun `when initialized, repository emits loading and data`() = runTest {
        // arrange
        val viewModel = MyViewModel(repository)
        val users = listOf(...)
        // 初始值应该是UiState.Loading,因为stateFlow可以直接获取最新值,此处直接做断言
        assertEquals(UiState.Loading, viewModel.userFlow.value)

        // action
        repository.sendUsers(users)
        viewModel.onRefresh()

        //check
        assertEquals(UiState.Success(users), viewModel.userFlow.value)
    }
}

// Mock UserRepository
class TestUserRepository : UserRepository {

  /**
   * The backing hot flow for the list of users for testing.
   */
  private val usersFlow =
    MutableSharedFlow<List<User>>(replay = 1, onBufferOverflow = BufferOverflow.DROP_OLDEST)

  override fun getUsers(): Flow<List<User>> {
    return usersFlow
  }

  /**
   * A test-only API to allow controlling the list of users from tests.
   */
  suspend fun sendUsers(users: List<User>) {
    usersFlow.emit(users)
  }
}

如果ViewModel中使用的是stateIn拓展函数:

@OptIn(ExperimentalCoroutinesApi::class)
@Test
fun `when initialized, repository emits loading and data`() = runTest {
    //arrange
    val viewModel = MainWithStateinViewModel(repository)
    val users = listOf(...)
    //action
    // 因为此时collect操作并不是在ViewModel中,我们需要在测试代码中执行collect
    val collectJob = launch(UnconfinedTestDispatcher(testScheduler)) {
        viewModel.userFlow.collect()
    }
    //check
    assertEquals(UiState.Loading, viewModel.userFlow.value)
    //action
    repository.sendUsers(users)
    //check
    assertEquals(UiState.Success(users), viewModel.userFlow.value)

    collectJob.cancel()
}

2.测试SharedFlow

测试SharedFlow可以使用一个开源库Turbine,Turbine是一个用于测试Flow的小型开源库。

测试使用sharedIn拓展函数的SharedFlow:

@OptIn(ExperimentalCoroutinesApi::class)
@Test
fun `when initialized, repository emits loading and data`() = runTest {
    val viewModel = MainWithShareInViewModel(repository)

    val users = listOf(...)
    repository.sendUsers(users)

    viewModel.userFlow.test {
        val firstItem = awaitItem()
        assertEquals(UiState.Loading, firstItem)

        val secondItem = awaitItem()
        assertEquals(UiState.Success(users), secondItem)
    }
}

img
img
img

既有适合小白学习的零基础资料,也有适合3年以上经验的小伙伴深入学习提升的进阶课程,涵盖了95%以上软件测试知识点,真正体系化!

由于文件比较多,这里只是将部分目录截图出来,全套包含大厂面经、学习笔记、源码讲义、实战项目、大纲路线、讲解视频,并且后续会持续更新

需要这份系统化的资料的朋友,可以戳这里获取

]
[外链图片转存中…(img-NpNJGwvo-1715885094294)]

既有适合小白学习的零基础资料,也有适合3年以上经验的小伙伴深入学习提升的进阶课程,涵盖了95%以上软件测试知识点,真正体系化!

由于文件比较多,这里只是将部分目录截图出来,全套包含大厂面经、学习笔记、源码讲义、实战项目、大纲路线、讲解视频,并且后续会持续更新

需要这份系统化的资料的朋友,可以戳这里获取

  • 17
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值