l

    Lilly

    2 years ago
    Hi, Is it possible to have state
    val isScanning: Boolean by viewModel.isScanning.collectAsState() // viewModel.isScanning is of type StateFlow<Boolean>
    without an initial value? I have multiple locations where this behaviour makes me trouble. Or to be more concrete: When I write something like this below my state:
    if (isScanning) viewModel.stopScan() else viewModel.startScan()
    it should not trigger
    stopScan()
    nor
    startScan()
    when composable function is called. Instead it should trigger on next value change.
    l

    Leland Richardson [G]

    2 years ago
    there should be a StateFlow-specific overload fof collectAsState that does not need an initial value.
    but if startScan()/stopScan() are non-idempotent methods with side effects, you should consider doing the following instead: if (isScanning) onCommit { startScan() onDispose { stopScan() } }
    l

    Lilly

    2 years ago
    @Leland Richardson [G] I couldn't find
    StateFlow-specific overload fof collectAsState that does not need an initial value.
    I'm on dev14 and kotlin 1.3.72. The onCommit callback looks interesting. Can you please explain, when it's triggered, I don't understand the description of the documentation.
    Timo Drick

    Timo Drick

    2 years ago
    OnCommit is triggered when the Composable component is added to the composition and onDispose when it is removed. So at the end more or less when the component gets visible and when it is removed.
    It is similar to the lifecycle in fragments or acitvities resume() -> pause()
    Sean McQuillan [G]

    Sean McQuillan [G]

    2 years ago
    onCommit will work here, though if this change is not driven by a UI event so the subscription and starting scan could be done outside of composition completely (perhaps in the ViewModel).