public class YourViewModel {
private WeakReference<Lifecycle> lifeCycle;
public YourViewModel(LifeCycle liefcycle){
this.lifeCycle = new WeakReference<>(lifecycle);
}
@OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
if(this.lifeCycle.get() != null){
// do cancel your network request here
}
}
// your activity
public class YourActivity extends AppCompatActivity {
YourViewModel viewModel;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
viewModel = new YourViewModel(this.getLifeCycle());
}
}
我认为您可以监控主机容器(活动或片段)的生命周期,并在销毁通知事件中取消网络请求操作。