【发布时间】:2019-11-08 21:14:28
【问题描述】:
我正在尝试使用数据绑定在 Kotlin 中实现 MVVM 架构。该代码仅显示空白屏幕作为输出。谁能帮我弄清楚为什么在执行这个程序时没有调用服务器。
我尝试了this 和与此类似的链接来解决问题。
我的代码如下:
主活动
class MainActivity : AppCompatActivity() {
private var cvViewModel: CvViewModel? = null
private var model: Model?= null
private var liveData: LiveData<Model>? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val binding : ActivityMainBinding= DataBindingUtil.setContentView(this, R.layout.activity_main)
// setContentView(R.layout.activity_main)
cvViewModel= ViewModelProviders.of(this).get(CvViewModel::class.java)
liveData= cvViewModel.getNewsRepository()
}
}
类 CvRepository {
private val apiCall: ApiCall=
RetrofitClient.cteateService(ApiCall::class.java)
fun getCvDetails(): MutableLiveData<Model> {
val cvData = MutableLiveData<Model>()
apiCall.getCvData().enqueue(object : Callback<Model> {
override fun onResponse(call: Call<Model>,
response: Response<Model>
) {
if (response.isSuccessful) {
Log.e("abc", ""+response.body().toString())
cvData.value = response.body()
}
}
override fun onFailure(call: Call<Model>, t: Throwable) {
cvData.value = null
}
})
return cvData
}
companion object {
private var cvRepository: CvRepository ? = null
val instance: CvRepository
get() {
if (cvRepository == null) {
cvRepository = CvRepository()
}
return this.cvRepository as CvRepository
}
}
}
class CvViewModel: ViewModel(){
private var mutableLiveData: MutableLiveData<Model>? = null
private var cvRepository: CvRepository? = null
fun init() {
if (mutableLiveData != null) {
return
}
cvRepository = CvRepository.instance
mutableLiveData = cvRepository!!.getCvDetails()
}
fun getNewsRepository(): LiveData<Model>? {
return mutableLiveData
}
}
【问题讨论】:
-
其实是同步的问题
标签: android kotlin mvvm retrofit