嘿,我正在学习 kotlin 中的流程。我正在学习MutableStateFlow和MutableSharedFlow。我试图在现实世界的例子中学习MutableStateFlow 。但我无法获得MutableSharedFlow示例,它更适合哪个位置。我尝试了一些MutableStateFlow
例如,当我们从 api 获取数据时,我们可以使用 seal 类进行相应的填充。
LoggedState.kt
sealed class LoggedState {
data class OnSuccess(val data: List<XYZ>) : LoggedState()
object OnEmpty : LoggedState()
data class IsLoading(val isLoading: Boolean = true) : LoggedState()
data class OnError(val message: String) : LoggedState()
}
SettingsViewModel.kt
class SettingsViewModel : ViewModel() {
var loggedMutableStateFlow = MutableStateFlow<LoggedState>(LoggedState.OnEmpty)
fun fetchData(){
val result = dataRepository.getLogged()
result.handleResult(
onSuccess = { response ->
val data = response?.items
if (!data.isNullOrEmpty()) {
loggedMutableStateFlow.value = LoggedState.OnSuccess(data)
} else {
loggedMutableStateFlow.value = LoggedState.OnEmpty
}
},
onError = {
loggedMutableStateFlow.value = LoggedState.OnError(it.message)
}
)
}
}
活动.kt
lifecycleScope.launchWhenCreated {
repeatOnLifecycle(Lifecycle.State.CREATED) {
viewModel.loggedMutableStateFlow.collect { state ->
when (state) {
is LoggedState.OnEmpty -> {
// view gone
}
is LoggedState.OnSuccess -> {
// show ui
}
is LoggedState.IsLoading -> {
// show spinner
}
is LoggedState.OnError-> {
// show error message
}
}
}
}
}
我都得到了MutableStateFlow示例。有人可以指导我如何在现实世界的例子中做MutableSharedFlow 。我也对参数很好奇
重播
额外缓冲容量
onBufferOverflow
谢谢