<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Ic Ks on Medium]]></title>
        <description><![CDATA[Stories by Ic Ks on Medium]]></description>
        <link>https://medium.com/@der.x?source=rss-3d57ad4f8ff9------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*NshZwY1lEM22_PKl.jpg</url>
            <title>Stories by Ic Ks on Medium</title>
            <link>https://medium.com/@der.x?source=rss-3d57ad4f8ff9------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 06:39:25 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@der.x/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Restartable StateFlows (in Compose)]]></title>
            <link>https://medium.com/@der.x/restartable-stateflows-in-compose-46316ce670a9?source=rss-3d57ad4f8ff9------2</link>
            <guid isPermaLink="false">https://medium.com/p/46316ce670a9</guid>
            <category><![CDATA[kotlin-flow]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[kotlin-coroutines]]></category>
            <category><![CDATA[compose]]></category>
            <dc:creator><![CDATA[Ic Ks]]></dc:creator>
            <pubDate>Sat, 25 Nov 2023 15:17:16 GMT</pubDate>
            <atom:updated>2023-11-25T15:19:10.995Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_-i5Vf6oeGeNc_hC.jpg" /></figure><p>If StateFlows&lt;T&gt;, SharingStarted.WhileSubscribed(4711), and ViewModels are your daily bread, feel free to jump straight to the restart implementation <a href="#5365">below</a> and skip the intro 🧐 If you&#39;re a code enthusiast who prefers to skip the natural language clutter, open the minimal working example on <a href="https://github.com/Ic-ks/restartable-flow">GitHub</a>.</p><h3>Intro</h3><p>Compose screens often display asynchronously loaded data provided as StateFlow&lt;ScreenState&gt; by a ViewModel. It&#39;s inevitable that exceptions might occur during data retrieval, prompting the question of how to recover from errors. While a user-triggered retry provides a simple solution, implementing it with Flow.retryWhen {...} becomes less satisfying, especially when dealing with it for every screen. This dissatisfaction grows further when you need to handle a second case: a user-triggered refresh without an error.</p><p>If you&#39;re tired of writing boilerplate code repeatedly, you&#39;ve come to the right place. Solving this problem requires only a few lines of code, but first, let&#39;s explore some minimal working example code to gain a better understanding of the issue.</p><h4>Defining Screen States</h4><p>To model clear states for the screen, we require three: a loading state, an error state, and, finally, a state containing the fetched data:</p><pre>sealed interface ProductScreenState {<br>    object Loading: ProductScreenState<br>    object Error: ProductScreenState<br>    @Immutable<br>    data class Description(val description: String): ProductScreenState<br>}</pre><h4>Implementing the ViewModel</h4><p>Our ViewModel consists of a StateFlow that reflects the fetching process with the help of the three states.</p><pre>class ProductScreenViewModel : ViewModel() {<br>    val productStream = flow {<br>        emit(ProductScreenState.Loading)<br>        emit(ProductScreenState.Description(fetchDescription()))<br>    }.catch {<br>        emit(ProductScreenState.Error)<br>    }.stateIn(<br>        scope = viewModelScope,<br>        started = SharingStarted.WhileSubscribed(5000),<br>        initialValue = ProductScreenState.Loading<br>    )<br><br>    private suspend fun fetchDescription(): String {<br>        delay(1500)<br>        require(Math.random() &gt; 0.5) { &quot;Random error&quot; }<br>        return &quot;My Product Description&quot;<br>    }<br>}</pre><p><strong>Currently, there isn’t a built-in mechanism for a user-triggered restart of the flow in both cases: in the event of fetching failures or when the user wishes to refresh the screen after a while.</strong></p><figure><img alt="Angry Meme" src="https://cdn-images-1.medium.com/max/189/1*NXD4zXS5vTcgo7uAPD7aqQ.png" /></figure><h4>Wait, We Missed an Important Detail</h4><p>Let’s take a closer look at this line:</p><p>started = SharingStarted.WhileSubscribed(5000).</p><p>It instructs the StateFlow to initiate state emission as soon as there is at least one subscriber. Moreover, it plays a crucial role in <strong>restarting</strong> 🎉 the flow when there are no subscriptions and a new subscription occurs. This happens when the time between zero subscriptions and the arrival of a new subscription exceeds 5 seconds. Quite intriguing, isn&#39;t it...</p><figure><img alt="Thinking Meme" src="https://cdn-images-1.medium.com/max/188/1*5_l7gEHmqUWTniCUWs6wsw.png" /></figure><p>Examining the source code of SharingStarted.WhileSubscribed(5000), we find that the logic is implemented in the following <a href="https://cs.android.com/android/platform/superproject/main/+/main:external/kotlinx.coroutines/kotlinx-coroutines-core/common/src/flow/SharingStarted.kt;drc=ca095beacadbdfa133f7d8d6931726bdf588a29a;l=166">class</a>:</p><pre>// see external/kotlinx.coroutines/kotlinx-coroutines-core/common/src/flow/SharingStarted.kt<br><br>private class StartedWhileSubscribed: SharingStarted {<br>    // ...<br>    override fun command(subscriptionCount: StateFlow&lt;Int&gt;): Flow&lt;SharingCommand&gt; = subscriptionCount<br>        .transformLatest { count -&gt;<br>            if (count &gt; 0) {<br>                emit(SharingCommand.START)<br>            } else {<br>                delay(stopTimeout)<br>                if (replayExpiration &gt; 0) {<br>                    emit(SharingCommand.STOP)<br>                    delay(replayExpiration)<br>                }<br>                emit(SharingCommand.STOP_AND_RESET_REPLAY_CACHE)<br>            }<br>        }<br>        .dropWhile { it != SharingCommand.START } // don&#39;t emit any STOP/RESET_BUFFER to start with, only START<br>        .distinctUntilChanged()<br>    }<br>    //...<br>}</pre><p>So the emit(SharingCommand.STOP_AND_RESET_REPLAY_CACHE) stops the flow and discards the current state. Unfortunately, there is no public access to trigger this action manually. But wait, we can implement our own SharingStarted - it is a public interface. Even better would be an extension for all existing SharingStarted implementations ( StartedEagerly, StartedLazy, and StartedWhileSubscribed). Alright, let&#39;s define our extension as an interface that can be used as wrapper for the existing SharingStarted implementations.</p><h3>Make SharingStarted restartable 🚂🌊🌊🌊🌊</h3><pre>// SharingRestartable.kt<br><br>interface SharingRestartable: SharingStarted {<br>    fun restart()<br>}</pre><p>Now, we require an implementation of our interface. The only task is to emit a SharingCommand.STOP_AND_RESET_REPLAY_CACHE and a SharingCommand.START command as soon as our defined restart() is called. Everything else should be handled by the existing SharingStarted instance. This can be achieved by merging a new MutableSharedFlow&lt;SharingCommand&gt; which is responsible to trigger the restart and the existing flow of the wrapped instance:</p><pre>// SharingRestartable.kt<br><br>private data class SharingRestartableImpl(<br>    private val sharingStarted: SharingStarted,<br>): SharingRestartable {<br><br>    private val restartFlow = MutableSharedFlow&lt;SharingCommand&gt;(extraBufferCapacity = 2)<br><br>    override fun command(subscriptionCount: StateFlow&lt;Int&gt;): Flow&lt;SharingCommand&gt; {<br>        return merge(restartFlow, sharingStarted.command(subscriptionCount))<br>    }<br><br>    override fun restart() {<br>        restartFlow.tryEmit(SharingCommand.STOP_AND_RESET_REPLAY_CACHE)<br>        restartFlow.tryEmit(SharingCommand.START)<br>    }<br>}</pre><p>To leverage our new private implementation, we need some syntactic sugar in the form of an extension function:</p><pre>// SharingRestartable.kt<br><br>fun SharingStarted.makeRestartable(): SharingRestartable {<br>    return SharingRestartableImpl(this)<br>}</pre><p>Now, we can define our flow and access our new restart mechanism:</p><pre>class ProductScreenViewModel : ViewModel() {<br>    // 1. Init restarter<br>    private val restarter = SharingStarted.WhileSubscribed(5000).makeRestartable()<br>    <br>    val productStream = flow {<br>        //...<br>    }.catch {<br>        emit(ProductScreenState.Error)<br>    }.stateIn(<br>        started = restarter,  // 2. Enable restarting<br>        //...<br>    )<br><br>    fun restart() = restarter.restart() // 3. Expose restarting<br>    <br>    //...<br>}</pre><h3>Finally, Reduce the Boilerplate Even More by Providing a Restartable State Flow</h3><p>For this purpose, we need an interface that extends the existing StateFlow&lt;T&gt; by adding a restart function:</p><pre>// RestartableStateFlow.kt<br><br>interface RestartableStateFlow&lt;out T&gt; : StateFlow&lt;T&gt; {<br>    fun restart()<br>}</pre><p>Then we can utilize our SharingRestartable implementation in conjunction with a custom stateIn() extension function:</p><pre>// RestartableStateFlow.kt<br><br>fun &lt;T&gt; Flow&lt;T&gt;.restartableStateIn(<br>    scope: CoroutineScope,<br>    started: SharingStarted,<br>    initialValue: T<br>): RestartableStateFlow&lt;T&gt; {<br>    val sharingRestartable = started.makeRestartable()<br>    val stateFlow = stateIn(scope, sharingRestartable, initialValue)<br>    return object : RestartableStateFlow&lt;T&gt;, StateFlow&lt;T&gt; by stateFlow {<br>        override fun restart() = sharingRestartable.restart()<br>    }<br>}</pre><p>This leads to our final implementation:</p><pre>class ProductScreenViewModel : ViewModel() {<br>    val productStream = flow {<br>        emit(ProductScreenState.Loading)<br>        emit(ProductScreenState.Description(fetchDescription()))<br>    }.catch {<br>        emit(ProductScreenState.Error)<br>    }.restartableStateIn( // &lt;&lt;&lt; Switching to restartableStateIn() is everything we have to change<br>        scope = viewModelScope,<br>        started = SharingStarted.WhileSubscribed(5000),<br>        initialValue = ProductScreenState.Loading<br>    )<br><br>    private suspend fun fetchDescription(): String {<br>        // ...<br>    }<br>}</pre><p>Even the viewModel.restart() function was removed, because RestartableStateFlow.restart() function is already exposed by the flow to the UI layer. Let’s see the usage:</p><pre>@Composable<br>private fun ScreenContent(viewModel: ProductScreenViewModel) {<br>    val state = viewModel.productStream.collectAsState()<br>    when (val stateValue = state.value) {<br>        ProductScreenState.Loading -&gt; LoadingPanel()<br>        is ProductScreenState.Description -&gt; DescriptionPanel(stateValue.description)<br>        ProductScreenState.Error -&gt; ErrorPanel(<br>            onClickRestart = viewModel.productStream::restart // There we go :)<br>        ) <br>    }<br>}</pre><p>Your feedback is highly appreciated, especially if there are any flaws.</p><p><em>Originally published at </em><a href="https://github.com/Ic-ks/restartable-flow"><em>https://github.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=46316ce670a9" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>