Hey I am learning flow in kotlin. I am learning about MutableStateFlow and MutableSharedFlow. I tried to learn MutableStateFlow in real world example. But I am unable to get the MutableSharedFlow example, which place it suits more. I tried some MutableStateFlow
For example when we are fetching data from api we can use seal class to populate accordingly .
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)
}
)
}
}
Activit.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
}
}
}
}
}
I all get the MutableStateFlow example. Can someone guide me how to do MutableSharedFlow in real world examples. Also I am curious about parameters
replay
extraBufferCapacity
onBufferOverflow
Thanks