2

I know that a Intent Service ends as soon as it's work is complete. I am making network calls on onHandleIntent().The service dies as soon as it starts but the network calls complete successfully.

Is it because all the methods for network calls are called and they exist in a different thread? So, the service dies?

@Override
protected void onHandleIntent(@Nullable Intent intent) {
    Log.i(TAG, "Download Service Started!");
    initVariables();
    startDownloadService(intent);
}

private void startDownloadService(Intent intent) {
    receiver = intent.getParcelableExtra("receiver");
    notifyDownloadRunning("Trying to start Download");

    getNews();
    getVideoDetails();
    .................
}

Retorfit Interface

@GET()
Observable<VideoDetailsRoot> getVideoDetails(@Url String url);
tynn
  • 38,113
  • 8
  • 108
  • 143
nishon.tan
  • 969
  • 2
  • 8
  • 21

1 Answers1

3

You're handling the threading twice. Once with the IntentService and once with Retrofit and Rx.

When subscribing to an Observable, you'll not block the current thread (most of the time) and instead wait for the result asynchronously.

In your case you can skip the implementation of the IntentService with good conscience. Retrofit and Rx provide you with enough capabilities to handle downloading asynchronously without blocking the main thread.

If you want to keep the service, you need to make the networking part synchronous or wait for the subscriptions to complete. But any of this might be a miss-use of Retrofit itself.

tynn
  • 38,113
  • 8
  • 108
  • 143
  • I start the service whenever there is a need to refresh data. What do you suggest so that my network calls call be made anywhere, without being attached with a activity or fragment ClassName.fetchdata() would be ideal – nishon.tan Jun 27 '17 at 12:47
  • You don't need a context, only a reference to the Retrofit service. If you need a context provide it as parameter. So just encapsulate it somehow (however you like ;) and provide it as a dependency whenever you need it. I'd suggest you not to implement it statically. But it's possible of course. – tynn Jun 27 '17 at 13:06
  • Oh a small leak can sink a ship. By attached i meant how i call write getNewsFrom() once and that could be called either on splashsceen, pull to refresh or on notification click. Do you think it's viable if i wrote static methods for api calls. I would then call them once a event like pull to refresh or anything happens – nishon.tan Jun 27 '17 at 13:26
  • Have a look at dependency injection and repository pattern. It's an extensive topic which I'm not able to cover with a single comment or a simple answer. But generally speaking: try to avoid static implementations. – tynn Jun 27 '17 at 13:30
  • Thanks! I will :) – nishon.tan Jun 27 '17 at 13:31