title: Jetpack Compose: How to change theme from light to dark mode programmatically onClick
body: <p>TL;DR change the theme and recompose the app between light and dark themes onClick.</p>
  <p>Hello! I have an interesting issue I have been struggling to figure out and would love some help. I am trying to implement a settings screen which lets the user change the theme of the app (selecting Dark, Light, or Auto which matches system setting).</p>
  <p>I am successfully setting the theme <strong>dynamically</strong> via invoking the <strong>isSystemInDarkTheme()</strong> function when choosing the color palette, but am struggling to <strong>recompose</strong> the app between light and dark themes on the click of a button.</p>
  <p>My strategy now is to create a theme model which hoists the state from the settings component which the user actually chooses the theme in. This theme model then exposes a theme state variable to the custom theme (wrapped around material theme) to decide whether to pick the light or dark color palette. Here is the relevant code --&gt;</p>
  <p>Theme</p>
  <pre><code>@Composable
  fun CustomTheme(
  themeViewModel: ThemeViewModel = viewModel(),
  content: @Composable() () -&gt; Unit,
  ) {
     val colors = when (themeViewModel.theme.value.toString()) {
         &quot;Dark&quot; -&gt; DarkColorPalette
         &quot;Light&quot; -&gt; LightColorPalette
         else -&gt; if (isSystemInDarkTheme()) DarkColorPalette else LightColorPalette
     }
  
     MaterialTheme(
         colors = colors,
         typography = typography,
         shapes = shapes,
         content = content
     )
     }
  </code></pre>
  <p>Theme model and state variable</p>
  <pre><code>class ThemeViewModel : ViewModel() {
  private val _theme = MutableLiveData(&quot;Auto&quot;)
  val theme: LiveData&lt;String&gt; = _theme
  
  fun onThemeChanged(newTheme: String) {
      when (newTheme) {
          &quot;Auto&quot; -&gt; _theme.value = &quot;Light&quot;
          &quot;Light&quot; -&gt; _theme.value = &quot;Dark&quot;
          &quot;Dark&quot; -&gt; _theme.value = &quot;Auto&quot;
      }
  }
  }
  </code></pre>
  <p>Component (UI) code</p>
  <pre><code>@Composable
  fun Settings(
     themeViewModel: ThemeViewModel = viewModel(),
  ) {
     ...
     val theme: String by themeViewModel.theme.observeAsState(&quot;&quot;)
     ...
     ScrollableColumn(Modifier.fillMaxSize()) {
         Column {
          ...
          Card() {
              Row() {
                  Text(text = theme,
                      modifier = Modifier.clickable(
                          onClick = {
                              themeViewModel.onThemeChanged(theme)
                          }
                      )
                  )
              }
          }
     }
  </code></pre>
  <p>Thanks so much for your time and help! ***I have elided some code here in the UI component, it is possible I have left out some closure syntax in the process.</p>