问题很简短:使用ViewModel异步调用改造2会导致内存泄漏吗?
就像下面的例子一样。
ShowsAsynViewModel.java
公共类ShowsAsyncViewModel扩展了ViewModel {
private static final String TAG = "ShowsAsyncViewModel";
private MutableLiveData<List<Show>> shows;
public LiveData<List<Show>> getShows() {
if (shows == null) {
shows = new MutableLiveData<>();
loadShows();
}
return shows;
}
private void loadShows() {
// Do an asynchronous operation to fetch users.
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(TvMazeService.BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
TvMazeService service = retrofit.create(TvMazeService.class);
service.getShows().enqueue(new Callback<List<Show>>() {
@Override
public void onResponse(Call<List<Show>> call, Response<List<Show>> response) {
if (response.isSuccessful()) {
List<Show> showList = response.body();
if (showList != null) {
shows.setValue(showList);
}
} else {
Log.i(TAG, "onResponse: Error code: " + response.code() + " - error message: " + response.message());
}
}
@Override
public void onFailure(Call<List<Show>> call, Throwable t) {
t.printStackTrace();
Log.i(TAG, "onFailure: Failed to connect: " + t.getMessage());
}
});
}
}
RetrofitActivity.java
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_retrofit);
ShowsAsyncViewModel model = ViewModelProviders.of(this).get(ShowsAsyncViewModel.class);
model.getShows().observe(this, new Observer<List<Show>>() {
@Override
public void onChanged(@Nullable List<Show> shows) {
// Do something with the result
}
});
}
这就是我所注意到的。
答案 0 :(得分:0)
是的,它可能导致内存泄漏。
想象一个场景,其中您从附加到ViewModel
的{{1}}进行网络呼叫。在调用完成之前,不是为了更改配置而是通过调用Activity
来销毁该活动。
即使Activity和ViewModel都被破坏,该调用仍将继续执行。
为防止这种情况,您可以按以下方式修改finish()
(kotlin代码)
ShowsAsynViewModel.java