MVVM 的流程就是 Fragment 點擊事件 → ViewModel 執行事件 → Fragment 監聽狀態改變畫面
一樣在 Fragment 的onViewCreated
建立點擊事件
binding.upload.setOnClickListener {
viewModel.uploadHackmd()
}
因為 Post 是走副執行緒,所以直接用共常式執行,利用改變 _httpStatus 來決定畫面要顯示什麼
private var _httpStatus = MutableLiveData<String?>()
val httpStatus: LiveData<String?>
get() = _httpStatus
fun uploadHackmd() {
viewModelScope.launch {
HttpManager.INSTANCE.post(body,
token,
postUrl,
getApplication(),
object : HttpResponseListener {
override fun onFailure(status: String, responseBody: String) {
_httpStatus.postValue(status)
}
override fun onSuccess(responseBody: String) {
_httpStatus.postValue(BaseConstants.SUCCESS)
}
})
}
}
viewModel.httpStatus.observe(viewLifecycleOwner) { status ->
status?.let {
//這邊顯示上傳成功的畫面
}
}