android - 如何在 MVVM 中重试 API 调用
问题描述
我正在为我的 Android 应用程序使用 MVVM 模式。一切看起来都那么好。但是当发生网络错误时,我需要显示一个带有重试按钮的弹出消息,该按钮预计会再次调用该 API。问题是当单击重试按钮时,它不知道哪个 API 返回了该错误以重试。有人可以给我一个建议吗?
/**
* Created by Nguyen on 3/27/2019.
*
* This BaseFragment will contain the common functions which can be shared in all fragments.
* All of the fragments in the app should be extended from this class
*/
abstract class BaseFragment : Fragment() {
...
protected fun registerViewModel(viewModel: BaseViewModel) {
...
viewModel.noNetworkErrorMessage().observe(this, Observer {
it.consume {
// I can add a listener here to handle when the Retry
// button is clicked
DialogHelper.showNoInternetConnectionDialog(context)
}
})
...
viewModel.timedOutMessage().observe(this, Observer {
it.consume {
DialogHelper.showAutoDismissErrorPopup(
context,
getString(R.string.error_request_time_out) {
// When the retry button is clicked
}
)
}
})
}
...
}
解决方案
如果您正在使用Retrofit
,您将从错误方法获得原始请求。因此,在您的视图模型的方法中,您可以传递 url。
所以场景将是:
YourViewModel extends ViewModel{
MutableLiveData<String> url;
.....
MutableLiveData<String> timedOutMessage(){
return url;
}
}
因此,当发生网络错误或超时错误时,请发送 url 以查看重试。
我想你会得到基本的想法。
推荐阅读
- swift - 从字符串中提取整个单词
- python - Selenium 无法使用 Python 在 Datepicker 字段上发送_keys
- android - Android WebView 在使用自定义键盘时出现 E/ActivityManager: ANR 错误
- azure-storage - 与组织内的多个用户共享 Azure 存储容器的最佳方式
- r - 链接到 Simple R markdown 网站上的其他页面
- c# - 列表中的值在修改 C# 时发生更改
- angular - GET unsafe:E:\project\Assessment of ....jpg net::ERR_UNKNOWN_URL_SCHEME
- android - 如何将我已经链接的 android 应用程序的 google firebase 更改为另一个 google firebase?
- python - 在python中只对那些彼此相邻的相同组进行分组的方法是什么?
- sql - 在 Athena 中是否有任何函数可以使 date 减去 bigint 类型?