我在Kotlin中使用MVVM体系结构。我创建了一个ViewModel和Repository类。在存储库类中,我正在使用翻新从API获取数据。我将数据存储到我的MutableLiveData对象中,但是在调试时,即使我的response.body不为null,该对象也始终显示为null。
我对Kotlin很陌生。请帮助..
ItemRepository.kt
class ItemRepository {
companion object{
private var instance: ItemRepository? = null
private var itemMutableList: MutableLiveData<List<ItemItem>>? = null
fun getinstance(): ItemRepository {
if (instance == null){
instance = ItemRepository()
}
return instance as ItemRepository
}
}
fun getItems() :MutableLiveData<List<ItemItem>>?{
var itemCall : Call<List<ItemItem>?> = ApiClient.getInstance()!!.getApi()!!.getIteams();
itemCall.enqueue(object : Callback<List<ItemItem>?> {
override fun onFailure(call: Call<List<ItemItem>?>, t: Throwable) {
}
override fun onResponse(call: Call<List<ItemItem>?>, response: Response<List<ItemItem>?>) {
var itemItem = response.body()
itemMutableList?.value = itemItem
itemMutableList // showing null value
}
})
return itemMutableList
}
}
MainViewModel.kt
class MainViewModel : ViewModel {
private var itemMutableList : MutableLiveData<List<ItemItem>>? = null
private var itemRepository: ItemRepository? = null
constructor()
{
if(itemMutableList != null){
return
}
itemRepository = ItemRepository.getinstance()
itemMutableList = itemRepository?.getItems()
}
fun getResultList() : MutableLiveData<List<ItemItem>>? {
if(itemMutableList != null)
{
itemMutableList
}
return itemMutableList
}
}
MainActivity
class MainActivity : AppCompatActivity() {
private var mainViewModel: MainViewModel? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
mainViewModel = ViewModelProviders.of(this).get(MainViewModel::class.java)
mainViewModel?.getResultList()?.observe(this, Observer { itmList ->
})
}
}
您尚未初始化itemMutableList。这就是为什么您得到null的原因。
private var itemMutableList: MutableLiveData<List<ItemItem>> = MutableLiveData()
现在在响应函数中为其分配值:
override fun onResponse(call: Call<List<ItemItem>?>, response: Response<List<ItemItem>?>) {
var itemItem = response.body()
itemMutableList.postValue(itemItem)
}