Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fragments, setRetainInstance(true), and threaded libraries

Here, Dianne says that the old methods of retaining objects via onRetainNonConfigurationInstance() are now made obsolete by the fact that you can retain Fragment instances over configuration changes.

And here, in the API Demos for fragments, it shows how to use this method for maintaining threads after a configuration change.

I see that during a configuration change, when the Fragment might not be attached to any activity and the thread is done doing it's work, it's able to call wait() so that it doesn't try to deliver results while an Activity isn't attached. I find this very useful, and a great way to mitigate one of the more pain-in-the-butt problems with Android orientation changes.

However, if you're using a threaded library (an API library that uses a thread executor, for example), where you don't have access to wait() on said threads, how could we use this new feature to our advantage?

How can we ensure that messages won't be delivered while an activity is not attached?

I've been thinking of a way to maybe queue up messages and delivery them when a new Activity is attached, but I wanted to hit up you guys and see if you've already come up with some solutions.

Also, note, I've looked into the LoaderManager API, and it seems like it would be good for data that needs to be loaded when an Activity is shown, but not for something event based, like logging in via a button, etc.

like image 566
synic Avatar asked May 13 '11 18:05

synic


1 Answers

You could get around this issue using a higher level concurrency utility such as a Latch, which you could have all of your threads wait on until the new Activity is attached (just before they try to access the message queue to deliver their result).

Once the Activity is attached, you can release the Latch, allowing all the threads to deliver their results.

like image 113
SubmittedDenied Avatar answered Oct 06 '22 01:10

SubmittedDenied