微调器:使用onclick侦听器以编程方式选择项目

假设我有一个包含以下项目的微调器:“ A”,“ B”,“ C”。如果用户尚未选择任何内容,则微调器将显示“未知”。

STEP ONE, the user might have selected an item in the past. So I load data in the view model and hasSelectedSomething observes the LiveData (asynchronous call to BE that will update the LiveData) in view model:

viewModel.itemLiveData.observe(
        viewLifecycleOwner,
        Observer { item ->
            hasSelectedSomething = (item != "unknown")
        }
)

第二步现在,我设置了微调器。如果用户尚未选择任何内容,我希望在“未知”项目中选择微调框,否则,我希望在用户之前选择的任何位置选择它。

if(!hasSelectedSomething) {
    spinner.setSelection(itemAdapter.getPosition("unknown"))
} else {
    spinner.setSelection(itemAdapter.getPosition(viewModel.getItemString()))
}

STEP THREE I implement the spinner.onItemSelectedListener:

spinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
        override fun onItemSelected(parent: AdapterView<*>?, view: View?, pos: Int, id: Long) {
            val selectedItem = spinner.getItemAtPosition(pos) as String

            viewModel.updateItemWithSelection(selectedItem)
        }

        override fun onNothingSelected(parent: AdapterView<*>?) {}
}

MY PROBLEM is that LiveData's default value is "unknown" meaning the spinner starts at "unknown", that's intended. Then let's say the user has selected "B" in the past, so I programmatically set the spinner to "B". The problem is that .setSelection triggers onItemSelected which sets selection to whatever the pos is and at that time, the pos corresponds to "unknown". So what happens is that LiveData goes from "unknown" (default value) to "B" (result from call to BE) to "unknown" (onItemSelected had "unknown" selected so it passes that value to view model) again.

我该如何解决这个问题?如何正确设置微调器,使其处理默认值,用户选择和以前的选择?