【发布时间】:2015-04-04 05:25:57
【问题描述】:
在 Android 中使用 RxJava(或 RxAndroid 等)代替 AsyncTask 如何帮助防止上下文泄漏?在 AsyncTask 中,如果您执行它并且用户离开应用程序,则活动上下文可能为空,应用程序可能会崩溃。我听说 RxJava 在执行线程时可以帮助防止这种类型的崩溃。我还听说它可以比 AsyncTask 的 doInBackground 方法更好地处理错误(错误地处理错误)。大多数时候,如果出现任何故障,我只会在 doInBackground 中返回 null(例如),但我读过 RxJava 可以返回确切的错误并且不会泄漏。谁能举个例子?
这是一个关于 AsyncTask 崩溃的小演示,如果用户在尝试向 UI 报告结果时离开应用程序:
@SuppressWarnings("unused")
private class GetTask extends AsyncTask<Void, Void, Void> {
@Override
protected void onPostExecute(String result) {
pd = new ProgressDialog(getActivity().getApplicationContext());//can crash right here
pd.setTitle("Grabbing Track!");
pd.setMessage("Please wait...");
pd.setCancelable(false);
pd.setIndeterminate(true);
pd.show();
}}
这是一个 doInBackground 方法调用,它不会发出有用的错误:
@Override
protected String doInBackground(String... params) {
String myIntAsString = 1/0 + ""; //this should give an error (how do we report it to the caller??
//or if we are parsing json and it fails, how do we report it to the caller cleanly. Can RxJava help?
}
【问题讨论】:
-
你问这个很有趣,我刚读完这个:blog.danlew.net/2014/09/15/grokking-rxjava-part-1
标签: android memory-leaks android-asynctask rx-java