首页 > 解决方案 > 如何在 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
                    }
                )
            }
        })
    }
    ...
}

标签: androidmvvm

解决方案


如果您正在使用Retrofit,您将从错误方法获得原始请求。因此,在您的视图模型的方法中,您可以传递 url。

所以场景将是:

YourViewModel extends ViewModel{
  MutableLiveData<String> url;
  .....
  MutableLiveData<String> timedOutMessage(){
    return url;
}

} 

因此,当发生网络错误或超时错误时,请发送 url 以查看重试。

我想你会得到基本的想法。


推荐阅读