Davide C
04/12/2021, 1:52 PMarnaud.giuliani
04/13/2021, 8:53 AMLiveDataDavide C
04/13/2021, 9:56 AMStateFlow//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()
    }
}redux-kotlinStateFlowclass 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)
    }
}@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")
        }
    }
}DataFlowAndroidDataFlowStateFlowLiveData