Reputation: 3048
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
?
Upvotes: 4
Views: 4487
Reputation: 326
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
})
...
}
Upvotes: 6