Davide C
04/12/2021, 1:52 PMarnaud.giuliani
04/13/2021, 8:53 AMLiveData
store on iOSDavide C
04/13/2021, 9:56 AMStateFlow
on iOS
• What I'm trying to achieve is a "shared view model"
//COMMON
expect abstract class AViewModel() {
val viewModelScope: CoroutineScope
protected open fun onCleared()
}
//ANDROID
actual abstract class AViewModel : ViewModel() {
actual val viewModelScope: CoroutineScope = androidViewModelScope
actual override fun onCleared() {
super.onCleared()
}
}
//iOS
actual abstract class AViewModel {
actual val viewModelScope: CoroutineScope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate)
protected actual open fun onCleared() {
viewModelScope.cancel()
}
}
• At the moment i'm wrapping redux-kotlin
with this "shared view model" exposing state via StateFlow
, here's a (very) simple example
class LauncherViewModel(
private val store: Store<AppState>,
) :
AViewModel() {
private val mutableStateFlow: MutableStateFlow<LauncherState> = MutableStateFlow(store.state.launcher)
private val unsubscribe: StoreSubscription = store.subscribe {
if (mutableStateFlow.value !== store.state.launcher)
mutableStateFlow.value = store.state.launcher
}
val state: StateFlow<LauncherState> = mutableStateFlow
override fun onCleared() {
unsubscribe()
}
fun toggle() {
store.dispatch(LauncherAction.ToggleLoading)
}
}
and on Android side
@Composable
fun LauncherScreen(viewModel: LauncherViewModel = getViewModel()) {
val state by remember(viewModel) { viewModel.state }.collectAsState()
LauncherContent(state = state) {
viewModel.toggle()
}
}
@Composable
fun LauncherContent(state: LauncherState, onButtonClick: () -> Unit) {
Column {
Text(text = state.isLoading.toString())
Button(onClick = onButtonClick) {
Text(text = "Next")
}
}
}
I'd like to replace redux-kotlin with uniflow-kt which i find neat and concise, furhtermore with the "shared view model" it would be natural to extend DataFlow
like AndroidDataFlow
. Do you think it's feasible expose state and events via StateFlow
(or other flows) rather than LiveData
?