0

So, I've implement sync mechanism, that uses Runnable. The thing with Runnable is, that you have to make sure it's properly created and destroyed in Activity. What happens if you have alot of activities? - Alot of boilerplate code.

Is there a way to create a single instance Runnable for whole application? Is it okay to initialize it in SomeClass extends Application as its app entry point? If so, how would one solve cases as such: SomeClass.onCreate() will hit even if user receives notification (that would also mean, that sync happens every time user gets a notification - which is terrible).

MaaAn13
  • 264
  • 5
  • 24
  • 54

1 Answers1

0

Why don't you using life cycle aware app component like - LiveData and ViewModel from android app architecture components. This is the best solution with AsyncTask.

With Runnable you don't have any control to stop or resume your execution with activity lifecycle. Because if a Runnable doing task in background it will complete any how and it causes defenitly memory leak.

Another easy solution is you can try using RxJava and RxAndroid, so simple in less code, see this.

And if you still want traditional way you can try this.

Bajrang Hudda
  • 3,028
  • 1
  • 36
  • 63
  • The network request is done using RxJava2. I dont see how your answer is applicable to my case. I'm using Runnable as a "timer" that executes network requests. The question is - how to make sure to use only one/single Runnable throughout whole application and avoid using multiple instances in multiple activities. – MaaAn13 Dec 03 '18 at 14:20
  • Are you not using any networking library for network request? – Bajrang Hudda Dec 03 '18 at 14:26