Is it possible to construct ArrayAdapter for Spinner from LiveData<List<T>> instead of normally List<T>?
What is the best practice to bind a ViewModel's LiveData returned value to a Spinner?
If It is exactly what do you mean, so:
class MyVM : ViewModel() {
...
private val mSpinnerData = MutableLiveData<List<String>>()
...
fun fetchSpinnerItems(): LiveData<List<String>> {
//fetch data
mSpinnerData.value = <some fetched list of Strings>
return mSpinnerData
}
}
And after in your activity/fragment:
class MyActivity : AppCompatActivity() {
private lateinit var mViewModel: MyVM
...
override fun onCreate(outState: Bundle?) {
//initialize your view model here...
mViewModel.fetchSpinnerItems().observe(this, Observer { spinnerData ->
val spinnerAdapter = ArrayAdapter(this, android.R.layout.simple_spinner_item, spinnerData)
mSpinner.adapter = spinnerAdapter
})
...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With