{"id":863,"date":"2023-10-07T08:08:26","date_gmt":"2023-10-07T08:08:26","guid":{"rendered":"https:\/\/androidpro.io\/?p=863"},"modified":"2023-10-07T08:13:58","modified_gmt":"2023-10-07T08:13:58","slug":"stateflow-vs-sharedflow","status":"publish","type":"post","link":"https:\/\/androidpro.io\/stateflow-vs-sharedflow\/","title":{"rendered":"StateFlow vs SharedFlow"},"content":{"rendered":"\n<p>What&#8217;s the difference between SharedFlow and StateFlow? That&#8217;s actually a very common interview question. And here&#8217;s how you can answer it:<\/p>\n\n\n\n<p>Both <code>SharedFlow<\/code> and <code>StateFlow<\/code> are hot streams, but they serve slightly different purposes. Let&#8217;s answer with practical examples to better understand their use cases.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">SharedFlow<\/h3>\n\n\n\n<p><code>SharedFlow<\/code> is like a <strong>broadcast channel<\/strong>. It can emit multiple values, and multiple collectors can listen to those values. It doesn&#8217;t have an initial value, but you can set how many values you want to replay to new collectors.<\/p>\n\n\n\n<p><strong>Example:<\/strong> Imagine a chat application where users can send messages. When a user sends a message, all online users should receive it. <code>SharedFlow<\/code> can be used to broadcast these messages to all online users.<\/p>\n\n\n\n<pre class=\"wp-block-prismatic-blocks\"><code class=\"language-kotlin\">val messagesFlow: SharedFlow&lt;String&gt; = MutableSharedFlow()\n\n\/\/ User A sends a message\nlaunch {\n    messagesFlow.emit(&quot;Hello from User A!&quot;)\n}\n\n\/\/ User B and User C are listening to the messages\nlaunch {\n    messagesFlow.collect { message -&gt;\n        println(&quot;User B received: $message&quot;)\n    }\n}\n\nlaunch {\n    messagesFlow.collect { message -&gt;\n        println(&quot;User C received: $message&quot;)\n    }\n}\n\n<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">StateFlow<\/h3>\n\n\n\n<p><code>StateFlow<\/code> is a <strong>state holder<\/strong>. It always has a value (initial or updated), and it emits the latest value to its collectors. It&#8217;s useful when you want to represent a piece of state that can change over time.<\/p>\n\n\n\n<p><strong>Example:<\/strong> Consider a music player app. The player has a state (playing, paused, stopped). You can use <code>StateFlow<\/code> to represent and observe the current state of the player.<\/p>\n\n\n\n<pre class=\"wp-block-prismatic-blocks\"><code class=\"language-kotlin\">val playerState: StateFlow&lt;PlayerState&gt; = MutableStateFlow(PlayerState.STOPPED)\n\n\/\/ Somewhere in the app, the state changes\nlaunch {\n    playerState.value = PlayerState.PLAYING\n}\n\n\/\/ Another part of the app observes the player&#039;s state\nlaunch {\n    playerState.collect { state -&gt;\n        when (state) {\n            PlayerState.PLAYING -&gt; println(&quot;Music is playing!&quot;)\n            PlayerState.PAUSED -&gt; println(&quot;Music is paused!&quot;)\n            PlayerState.STOPPED -&gt; println(&quot;Music is stopped!&quot;)\n        }\n    }\n}\n\n<\/code><\/pre>\n\n\n\n<p>In this example, whenever the player&#8217;s state changes, the observing part of the app will react accordingly.<\/p>\n\n\n\n<p>While both <code>SharedFlow<\/code> and <code>StateFlow<\/code> can be used to emit and collect values, <code>SharedFlow<\/code> is <strong>more general<\/strong> and can be used for broadcasting multiple values to multiple collectors. In contrast, <code>StateFlow<\/code> is specialized for representing and observing state changes.<\/p>\n\n\n\n<p>In the context of <strong>Android development<\/strong>, <strong><code>StateFlow<\/code><\/strong> is particularly beneficial when used with Jetpack Compose and ViewModels. It provides a seamless way to observe and react to state changes in the UI, ensuring that the view layer always reflects the latest application state.<\/p>\n\n\n\n<p><strong>tl;dr:<\/strong> <code>SharedFlow<\/code> broadcasts multiple values to many collectors, like chat messages to users. <code>StateFlow<\/code> holds and emits the latest state, like a music player&#8217;s status. Both are hot streams with distinct use cases.<\/p>\n\n\n\n<div class=\"wp-block-group alignfull\" style=\"margin-top:0px;margin-bottom:0px;padding-top:48px;padding-bottom:48px\"><div class=\"wp-block-group__inner-container is-layout-constrained wp-block-group-is-layout-constrained\">\n<div class=\"wp-block-columns alignwide has-ti-bg-alt-background-color has-background is-layout-flex wp-container-core-columns-is-layout-53642b31 wp-block-columns-is-layout-flex\" style=\"padding-top:0;padding-right:0;padding-bottom:0;padding-left:0\">\n<div class=\"wp-block-column is-vertically-aligned-center is-layout-flow wp-block-column-is-layout-flow\" style=\"padding-top:var(--wp--preset--spacing--50);padding-right:var(--wp--preset--spacing--50);padding-bottom:var(--wp--preset--spacing--50);padding-left:var(--wp--preset--spacing--50);flex-basis:50%\">\n<h6 class=\"wp-block-heading has-ti-accent-color has-text-color\" style=\"text-transform:uppercase\">Comprehensive guide to Android Interview<\/h6>\n\n\n\n<h3 class=\"wp-block-heading\">Android Interview Pro<\/h3>\n\n\n\n<p>Ready to ace your Android developer interview? Get your hands on our comprehensive eBook today and start preparing\u00a0with confidence.<\/p>\n\n\n\n<div class=\"wp-block-buttons has-custom-font-size has-normal-font-size is-layout-flex wp-block-buttons-is-layout-flex\">\n<div class=\"wp-block-button\"><a class=\"wp-block-button__link wp-element-button\" href=\"https:\/\/androidpro.io\/android-interview-pro\/\">Get it now<\/a><\/div>\n<\/div>\n\n\n\n<div style=\"height:20px\" aria-hidden=\"true\" class=\"wp-block-spacer\"><\/div>\n<\/div>\n\n\n\n<div class=\"wp-block-column is-layout-flow wp-block-column-is-layout-flow\">\n<figure class=\"wp-block-image size-large\"><img fetchpriority=\"high\" decoding=\"async\" width=\"1024\" height=\"1024\" src=\"https:\/\/androidpro.io\/wp-content\/uploads\/2023\/06\/Projekt-bez-nazwy-5-1024x1024.png\" alt=\"\" class=\"wp-image-126\" srcset=\"https:\/\/androidpro.io\/wp-content\/uploads\/2023\/06\/Projekt-bez-nazwy-5-1024x1024.png 1024w, https:\/\/androidpro.io\/wp-content\/uploads\/2023\/06\/Projekt-bez-nazwy-5-300x300.png 300w, https:\/\/androidpro.io\/wp-content\/uploads\/2023\/06\/Projekt-bez-nazwy-5-150x150.png 150w, https:\/\/androidpro.io\/wp-content\/uploads\/2023\/06\/Projekt-bez-nazwy-5-768x768.png 768w, https:\/\/androidpro.io\/wp-content\/uploads\/2023\/06\/Projekt-bez-nazwy-5.png 1200w\" sizes=\"(max-width: 1024px) 100vw, 1024px\" \/><\/figure>\n<\/div>\n<\/div>\n<\/div><\/div>\n\n\n","protected":false},"excerpt":{"rendered":"<p>What&#8217;s the difference between SharedFlow and StateFlow? That&#8217;s actually a very common interview question. And here&#8217;s how you can answer it: Both SharedFlow and StateFlow are hot streams, but they serve slightly different purposes. Let&#8217;s answer with practical examples to better understand their use cases. SharedFlow SharedFlow is like a broadcast channel. It can emit [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":866,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_eb_attr":"","footnotes":""},"categories":[1],"tags":[8,7],"class_list":["post-863","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-uncategorized","tag-interview-questions","tag-kotlin"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v21.0 - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>StateFlow vs SharedFlow - Android Pro<\/title>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/androidpro.io\/stateflow-vs-sharedflow\/\" \/>\n<meta property=\"og:locale\" content=\"en_GB\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"StateFlow vs SharedFlow - Android Pro\" \/>\n<meta property=\"og:description\" content=\"What&#8217;s the difference between SharedFlow and StateFlow? That&#8217;s actually a very common interview question. And here&#8217;s how you can answer it: Both SharedFlow and StateFlow are hot streams, but they serve slightly different purposes. Let&#8217;s answer with practical examples to better understand their use cases. SharedFlow SharedFlow is like a broadcast channel. It can emit [&hellip;]\" \/>\n<meta property=\"og:url\" content=\"https:\/\/androidpro.io\/stateflow-vs-sharedflow\/\" \/>\n<meta property=\"og:site_name\" content=\"Android Pro\" \/>\n<meta property=\"article:published_time\" content=\"2023-10-07T08:08:26+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2023-10-07T08:13:58+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/androidpro.io\/wp-content\/uploads\/2023\/10\/stateflow-shared-flow-1.jpg\" \/>\n\t<meta property=\"og:image:width\" content=\"1200\" \/>\n\t<meta property=\"og:image:height\" content=\"675\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/jpeg\" \/>\n<meta name=\"author\" content=\"Jaros\u0142aw Michalik\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Jaros\u0142aw Michalik\" \/>\n\t<meta name=\"twitter:label2\" content=\"Estimated reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"2 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"WebPage\",\"@id\":\"https:\/\/androidpro.io\/stateflow-vs-sharedflow\/\",\"url\":\"https:\/\/androidpro.io\/stateflow-vs-sharedflow\/\",\"name\":\"StateFlow vs SharedFlow - Android Pro\",\"isPartOf\":{\"@id\":\"https:\/\/androidpro.io\/#website\"},\"datePublished\":\"2023-10-07T08:08:26+00:00\",\"dateModified\":\"2023-10-07T08:13:58+00:00\",\"author\":{\"@id\":\"https:\/\/androidpro.io\/#\/schema\/person\/1c52a058fc09bbdce9021f1d89d7f9d1\"},\"breadcrumb\":{\"@id\":\"https:\/\/androidpro.io\/stateflow-vs-sharedflow\/#breadcrumb\"},\"inLanguage\":\"en-GB\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/androidpro.io\/stateflow-vs-sharedflow\/\"]}]},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/androidpro.io\/stateflow-vs-sharedflow\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\/\/androidpro.io\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"StateFlow vs SharedFlow\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\/\/androidpro.io\/#website\",\"url\":\"https:\/\/androidpro.io\/\",\"name\":\"Android Pro\",\"description\":\"\",\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\/\/androidpro.io\/?s={search_term_string}\"},\"query-input\":\"required name=search_term_string\"}],\"inLanguage\":\"en-GB\"},{\"@type\":\"Person\",\"@id\":\"https:\/\/androidpro.io\/#\/schema\/person\/1c52a058fc09bbdce9021f1d89d7f9d1\",\"name\":\"Jaros\u0142aw Michalik\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-GB\",\"@id\":\"https:\/\/androidpro.io\/#\/schema\/person\/image\/\",\"url\":\"https:\/\/secure.gravatar.com\/avatar\/708d1b2199cff06b8ce08b0b1acfaae2da833fe1b1e6c4ae84b8f73544c1b8d8?s=96&d=mm&r=g\",\"contentUrl\":\"https:\/\/secure.gravatar.com\/avatar\/708d1b2199cff06b8ce08b0b1acfaae2da833fe1b1e6c4ae84b8f73544c1b8d8?s=96&d=mm&r=g\",\"caption\":\"Jaros\u0142aw Michalik\"},\"sameAs\":[\"https:\/\/androidpro.io\"],\"url\":\"https:\/\/androidpro.io\/author\/michalik-admin\/\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"StateFlow vs SharedFlow - Android Pro","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/androidpro.io\/stateflow-vs-sharedflow\/","og_locale":"en_GB","og_type":"article","og_title":"StateFlow vs SharedFlow - Android Pro","og_description":"What&#8217;s the difference between SharedFlow and StateFlow? That&#8217;s actually a very common interview question. And here&#8217;s how you can answer it: Both SharedFlow and StateFlow are hot streams, but they serve slightly different purposes. Let&#8217;s answer with practical examples to better understand their use cases. SharedFlow SharedFlow is like a broadcast channel. It can emit [&hellip;]","og_url":"https:\/\/androidpro.io\/stateflow-vs-sharedflow\/","og_site_name":"Android Pro","article_published_time":"2023-10-07T08:08:26+00:00","article_modified_time":"2023-10-07T08:13:58+00:00","og_image":[{"width":1200,"height":675,"url":"https:\/\/androidpro.io\/wp-content\/uploads\/2023\/10\/stateflow-shared-flow-1.jpg","type":"image\/jpeg"}],"author":"Jaros\u0142aw Michalik","twitter_card":"summary_large_image","twitter_misc":{"Written by":"Jaros\u0142aw Michalik","Estimated reading time":"2 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"WebPage","@id":"https:\/\/androidpro.io\/stateflow-vs-sharedflow\/","url":"https:\/\/androidpro.io\/stateflow-vs-sharedflow\/","name":"StateFlow vs SharedFlow - Android Pro","isPartOf":{"@id":"https:\/\/androidpro.io\/#website"},"datePublished":"2023-10-07T08:08:26+00:00","dateModified":"2023-10-07T08:13:58+00:00","author":{"@id":"https:\/\/androidpro.io\/#\/schema\/person\/1c52a058fc09bbdce9021f1d89d7f9d1"},"breadcrumb":{"@id":"https:\/\/androidpro.io\/stateflow-vs-sharedflow\/#breadcrumb"},"inLanguage":"en-GB","potentialAction":[{"@type":"ReadAction","target":["https:\/\/androidpro.io\/stateflow-vs-sharedflow\/"]}]},{"@type":"BreadcrumbList","@id":"https:\/\/androidpro.io\/stateflow-vs-sharedflow\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/androidpro.io\/"},{"@type":"ListItem","position":2,"name":"StateFlow vs SharedFlow"}]},{"@type":"WebSite","@id":"https:\/\/androidpro.io\/#website","url":"https:\/\/androidpro.io\/","name":"Android Pro","description":"","potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/androidpro.io\/?s={search_term_string}"},"query-input":"required name=search_term_string"}],"inLanguage":"en-GB"},{"@type":"Person","@id":"https:\/\/androidpro.io\/#\/schema\/person\/1c52a058fc09bbdce9021f1d89d7f9d1","name":"Jaros\u0142aw Michalik","image":{"@type":"ImageObject","inLanguage":"en-GB","@id":"https:\/\/androidpro.io\/#\/schema\/person\/image\/","url":"https:\/\/secure.gravatar.com\/avatar\/708d1b2199cff06b8ce08b0b1acfaae2da833fe1b1e6c4ae84b8f73544c1b8d8?s=96&d=mm&r=g","contentUrl":"https:\/\/secure.gravatar.com\/avatar\/708d1b2199cff06b8ce08b0b1acfaae2da833fe1b1e6c4ae84b8f73544c1b8d8?s=96&d=mm&r=g","caption":"Jaros\u0142aw Michalik"},"sameAs":["https:\/\/androidpro.io"],"url":"https:\/\/androidpro.io\/author\/michalik-admin\/"}]}},"_links":{"self":[{"href":"https:\/\/androidpro.io\/wp-json\/wp\/v2\/posts\/863","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/androidpro.io\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/androidpro.io\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/androidpro.io\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/androidpro.io\/wp-json\/wp\/v2\/comments?post=863"}],"version-history":[{"count":4,"href":"https:\/\/androidpro.io\/wp-json\/wp\/v2\/posts\/863\/revisions"}],"predecessor-version":[{"id":870,"href":"https:\/\/androidpro.io\/wp-json\/wp\/v2\/posts\/863\/revisions\/870"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/androidpro.io\/wp-json\/wp\/v2\/media\/866"}],"wp:attachment":[{"href":"https:\/\/androidpro.io\/wp-json\/wp\/v2\/media?parent=863"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/androidpro.io\/wp-json\/wp\/v2\/categories?post=863"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/androidpro.io\/wp-json\/wp\/v2\/tags?post=863"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}