title: Spinner: selecting item programatically with an on click listener
body: <p>Let's say I have a spinner that has these items: &quot;A&quot;, &quot;B&quot;, &quot;C&quot;. The spinner displays &quot;unknown&quot; if the user hasn't selected anything yet.</p>
  <p><strong>STEP ONE</strong>, the user might have selected an item in the past. So I load data in the view model and <code>hasSelectedSomething</code> observes the <code>LiveData</code> (asynchronous call to BE that will update the <code>LiveData</code>) in view model:</p>
  <pre><code>viewModel.itemLiveData.observe(
          viewLifecycleOwner,
          Observer { item -&gt;
              hasSelectedSomething = (item != &quot;unknown&quot;)
          }
  )
  </code></pre>
  <p><strong>STEP TWO</strong> I now set up my spinner. I want the spinner to be selected at &quot;unknown&quot; item if the user hasn't selected anything yet, otherwise I want to have it selected at whatever the user selected before.</p>
  <pre><code>if(!hasSelectedSomething) {
      spinner.setSelection(itemAdapter.getPosition(&quot;unknown&quot;))
  } else {
      spinner.setSelection(itemAdapter.getPosition(viewModel.getItemString()))
  }
  </code></pre>
  <p><strong>STEP THREE</strong> I implement the <code>spinner.onItemSelectedListener</code>:</p>
  <pre><code>spinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
          override fun onItemSelected(parent: AdapterView&lt;*&gt;?, view: View?, pos: Int, id: Long) {
              val selectedItem = spinner.getItemAtPosition(pos) as String
  
              viewModel.updateItemWithSelection(selectedItem)
          }
  
          override fun onNothingSelected(parent: AdapterView&lt;*&gt;?) {}
  }
  </code></pre>
  <p><strong>MY PROBLEM</strong> is that <code>LiveData</code>'s default value is &quot;unknown&quot; meaning the spinner starts at &quot;unknown&quot;, that's intended. Then let's say the user has selected &quot;B&quot; in the past, so I programmatically set the spinner to &quot;B&quot;. The problem is that <code>.setSelection</code> triggers <code>onItemSelected</code> which sets selection to whatever the <code>pos</code> is and at that time, the <code>pos</code> corresponds to &quot;unknown&quot;. So what happens is that <code>LiveData</code> goes from &quot;unknown&quot; (default value) to &quot;B&quot; (result from call to BE) to &quot;unknown&quot; (onItemSelected had &quot;unknown&quot; selected so it passes that value to view model) again.</p>
  <p>How do I solve this problem? How do I properly set up the spinner so that it handles default value, user selection and previous selection?</p>