Hi! Are there any updates about Multiplatform?
# uniflow
d
Hi! Are there any updates about Multiplatform?
a
Yes, intersting topic. Would be great to see how we would implement a
LiveData
store on iOS
d
I'm on an early stage of learning multi-platform + declarative UI so probably there are some pitfalls in the prototipe i'm working on, nevertheless: • This article shows a way to collect a
StateFlow
on iOS • What I'm trying to achieve is a "shared view model"
Copy code
//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
Copy code
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
Copy code
@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
?