网上学习资料一大堆,但如果学到的知识不成体系,遇到问题时只是浅尝辄止,不再深入研究,那么很难做到真正的技术提升。
一个人可以走的很快,但一群人才能走的更远!不论你是正从事IT行业的老鸟或是对IT行业感兴趣的新人,都欢迎加入我们的的圈子(技术交流、学习资源、职场吐槽、大厂内推、面试辅导),让我们一起学习成长!
// started参数保证了当配置改变时不会重新触发订阅
}
在一些业务复杂的页面,比如首页,通常会有多个数据来源,也就有多个flow,为了保证单一可靠数据源原则,我们可以使用combine函数将多个flow组成一个flow,然后再使用stateIn函数转换成StateFlow。
shareIn拓展函数使用方式也是类似的,只不过没有初始值initialValue参数,此处不做赘述。
### **这两者如何选择?**
上文说到,我们应该在ViewModel中暴露出热流,现在我们有两个热流-StateFlow和SharedFlow,如何选择?
没什么特定的规则,选择的时候只需要想一下一下问题:
1.我真的需要在特定的时间、位置获取Flow的最新状态吗?
如果不需要,那考虑SharedFlow,比如常用的事件通知功能。
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.Loading)
val userFlow: StateFlow = _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>(replay = 1, onBufferOverflow = BufferOverflow.DROP_OLDEST)
override fun getUsers(): Flow<List> {
return usersFlow
}
/**
- A test-only API to allow controlling the list of users from tests.
*/
suspend fun sendUsers(users: List) {
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:
![img](https://img-blog.csdnimg.cn/img_convert/526cd572e142cd5eb8fc9e3bbc91aba7.png)
![img](https://img-blog.csdnimg.cn/img_convert/27990059bc606b16a5f5118181684a3d.png)
![img](https://img-blog.csdnimg.cn/img_convert/eb7b95eb1fdb1801bfa8468a9d60662b.png)
**既有适合小白学习的零基础资料,也有适合3年以上经验的小伙伴深入学习提升的进阶课程,涵盖了95%以上软件测试知识点,真正体系化!**
**由于文件比较多,这里只是将部分目录截图出来,全套包含大厂面经、学习笔记、源码讲义、实战项目、大纲路线、讲解视频,并且后续会持续更新**
**[需要这份系统化的资料的朋友,可以戳这里获取](https://bbs.csdn.net/topics/618631832)**
[外链图片转存中...(img-Y20AeyhK-1715885061428)]
**既有适合小白学习的零基础资料,也有适合3年以上经验的小伙伴深入学习提升的进阶课程,涵盖了95%以上软件测试知识点,真正体系化!**
**由于文件比较多,这里只是将部分目录截图出来,全套包含大厂面经、学习笔记、源码讲义、实战项目、大纲路线、讲解视频,并且后续会持续更新**
**[需要这份系统化的资料的朋友,可以戳这里获取](https://bbs.csdn.net/topics/618631832)**