我是靠谱客的博主 单纯哑铃,这篇文章主要介绍ViewModel中的StateFlow和SharedFlow,使用建议以及单元测试,现在分享给大家,希望可以做个参考。

StateFlow和SharedFlow都是kotlin中的数据流,官方概念简介如下:

StateFlow:一个状态容器式可观察数据流,可以向其收集器发出当前状态和新状态。是热数据流。

SharedFlow:StateFlow是StateFlow的可配置性极高的泛化数据流(StateFlow继承于SharedFlow)

对于两者的基本使用以及区别,此处不做详解,可以参考官方文档。本文会给出一些关于如何在业务中选择选择合适热流(hot flow)的建议,以及单元测试代码。

StateFlow的一般用法如下图所示:

以读取数据库数据为例,Repository负责从数据库读取相应数据并返回一个flow,在ViewModel收集这个flow中的数据并更新状态(StateFlow),在MVVM模型中,ViewModel中暴露出来的StateFlow应该是UI层中唯一的可信数据来源,注意是唯一,这点跟使用LiveData的时候不同。

我们应该在ViewModel中暴露出热流(StateFlow或者SharedFlow)而不是冷流(Flow)

如果我们如果暴露出的是普通的冷流,会导致每次有新的流收集者时就会触发一次emit,造成资源浪费。所以如果Repository提供的只有简单的冷流怎么办?很简单,将之转换成热流就好了!通常可以采用以下两种方式:

1、还是正常收集冷流,收集到一个数据就往另外构建的StateFlow或SharedFlow发送

2、使用stateIn或shareIn拓展函数转换成热流

既然官方给我们提供了拓展函数,那肯定是直接使用这个方案最好,使用方式如下:

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
private const val DEFAULT_TIMEOUT = 500L @HiltViewModel class MyViewModel @Inject constructor( userRepository: UserRepository ): ViewModel() { val userFlow: StateFlow<UiState> = userRepository .getUsers() .asResult() // 此处返回Flow<Result<User>> .map { result -> when(result) { is Result.Loading -> UiState.Loading is Result.Success -> UiState.Success(result.data) is Result.Error -> UiState.Error(result.exception) } } .stateIn( scope = viewModelScope, initialValue = UiState.Loading, started = SharingStarted.WhileSubscribed(DEFAULT_TIMEOUT) ) // 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'

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
// 收集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。

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
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单元测试代码中:

复制代码
1
2
3
4
5
6
7
class MyViewModelTest { @get:Rule val mainDispatcherRule = MainDispatcherRule() ... }

1.测试StateFlow

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

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
@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) } } } } } }

单元测试代码如下:

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
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拓展函数:

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
@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:

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
@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) } }

作者:linversion
链接:https://juejin.cn/post/7189176023362043965

最后

如果想要成为架构师或想突破20~30K薪资范畴,那就不要局限在编码,业务,要会选型、扩展,提升编程思维。此外,良好的职业规划也很重要,学习的习惯很重要,但是最重要的还是要能持之以恒,任何不能坚持落实的计划都是空谈。

如果你没有方向,这里给大家分享一套由阿里高级架构师编写的《Android八大模块进阶笔记》,帮大家将杂乱、零散、碎片化的知识进行体系化的整理,让大家系统而高效地掌握Android开发的各个知识点。

在这里插入图片描述
相对于我们平时看的碎片化内容,这份笔记的知识点更系统化,更容易理解和记忆,是严格按照知识体系编排的。

全套视频资料:

一、面试合集
在这里插入图片描述
二、源码解析合集

在这里插入图片描述
三、开源框架合集

在这里插入图片描述
欢迎大家一键三连支持,若需要文中资料,直接点击文末CSDN官方认证微信卡片免费领取↓↓↓

最后

以上就是单纯哑铃最近收集整理的关于ViewModel中的StateFlow和SharedFlow,使用建议以及单元测试的全部内容,更多相关ViewModel中内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(58)

评论列表共有 0 条评论

立即
投稿
返回
顶部