【问题标题】:How to communicate between viewModel and MainActivity through Databinding?viewModel和MainActivity如何通过Databinding进行通信?
【发布时间】: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


【解决方案1】:

CvRepository 中的getCvDetails() 返回空列表,因为enqueue 是异步的。这就是您的视图中没有填充数据的原因。

尝试直接将存储库 LiveData 从 ViewModel 传递给 Activity

fun getNewsRepository(): LiveData<Model>? {
    return CvRepository.instance.getCvDetails()
}

然后观察Activity的变化

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)

    ...

    liveData= cvViewModel.getNewsRepository()
    liveData?.observe(this, Observer { items ->
         //Do your operation here
    })
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多