Lost background tasks example

In a very similar way, as we've just explored with Memory Leaks, it is possible to lose control (and related resources) of Threads and Background Threads.

Let's update the code for MockActivity to have an Observable.interval():

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mock);

Observable.interval(0, 2, TimeUnit.SECONDS)
.subscribe(i -> Log.i("APP", "Instance " + this.toString()
+ " reporting"));

Log.i("APP", "Activity Created");
}

Now, let's start the Activity a few times. We will promptly see that there are a lot of messages in the logs, as shown:

APP: Instance packt.reactivestocks.MockActivity@3c57ddae reporting
APP: Instance packt.reactivestocks.MockActivity@384e56b3 reporting
APP: Instance packt.reactivestocks.MockActivity@1bee4cb9 reporting
APP: Instance packt.reactivestocks.MockActivity@2e074272 reporting
APP: Instance packt.reactivestocks.MockActivity@163c07f8 reporting
APP: Instance packt.reactivestocks.MockActivity@159d438f reporting

Note that all of them have different IDs, so they are different instances. So, in this case, we've not only leaked the Activity with its memory, but also the background tasks that we have just created stay there and work even though the result is irrelevant after the Activity is destroyed.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.178.151