2

Using Google's mvvm architecture components Github browser sample as a reference, how would one cancel a viewmodel hosted, live data observed, retrofit network request? :)

Maybe I'm reading it wrong, but if network conditions are poor and requests take for example 30 seconds, each request should be cancelled otherwise many requests might be launched if the app is opened and closed rapidly. How would a well designed app handle this?

The callback when the livedata observer is removed can be accessed by overriding onInactive here I think. I could try cancelling all calls here, but what if I don't want to cancel some calls for some reason?

I'm guessing Facebook doesn't cancel trying to load your feed when you hit the back button.

Daniel Wilson
  • 18,838
  • 12
  • 85
  • 135

1 Answers1

2
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());
    }
}

I think you can monitor the lifecycle of your host container(activity or fragment), and in the destory notify event, do cancel network request operations.

yu wang
  • 283
  • 1
  • 6
  • Right that seems like the way to do it, so I guess my question now is in Google's sample, how do you access the request? Those requests are like 3 layers deep inside the NetworkBoundResource inside a repository. Hmm... – Daniel Wilson Jan 05 '18 at 12:51
  • In your viewmodel you should have the repository, so just call repository to clear the network call. – yu wang Jan 08 '18 at 07:23
  • Right, but you can see the NetworkBoundResource the retrofit calls are tied up in right? They only expose an api request in the repository, such as `githubService.getRepo(owner, name);`. Maybe this is not a good pattern to follow because there is no direct access to the retrofit Call object – Daniel Wilson Jan 08 '18 at 12:11
  • Yes, you are right, i don't use google's sample pattern, but i think you could do some thing in the "LiveDataCallAdapter.java", modify it to expose the cancel function, just suggestion. – yu wang Jan 09 '18 at 03:06
  • This just shows how to pass a lifecycle to viewmodel, but doesn't show how to clear network request on repo. – zemaitis Oct 08 '18 at 15:42