如何通过数据绑定在viewModel和MainActivity之间进行通信?

时间:2019-11-08 21:14:28

标签: android kotlin mvvm retrofit

我正在尝试使用数据绑定在Kotlin中实现MVVM体系结构。该代码仅显示空白屏幕作为输出。有人可以帮我弄清楚为什么在执行此程序时没有对服务器的调用。

我尝试了this并使用类似的链接来解决此问题。

我的代码如下:

MainActivity

private void createDataBase () throws IOException {
     this.getReadableDatabase ();
     this.close ();
     try {
         copyDataBase ();
     } catch (IOException e) {
         throw new RuntimeException (e);
     }
}

}

CvRepository类{

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()
}

}

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
        }
}

}

1 个答案:

答案 0 :(得分:1)

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

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

enqueue

然后观察“活动”中的变化

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