Netflix/RxJava — pull request #427 by mttkay (2013-10-09 09:20:57+00:00)
Title: [RFC] Initial implementation of OperationObserveInForeground (Android)

In reference to the discussion in [0] and our work with RxJava on Android, here is an initial attempt at providing an Rx operator which wraps the boilerplate required to observe sequences on Android UI components like Fragments and Activities (although I should mention that I haven't added support for the latter yet but focused on Fragments from the support-v4 library.)

Here's what I did:
- provide an operator which accepts a specialized observer type that is able to expose a Fragment reference. This is essential for us to decide whether it's safe to forward messages to that fragment, and we can only ask the fragment itself to make that decision
- schedule observer callbacks on the Android UI thread by default

There is some discussions to be had around this. I would really appreciate if everyone with and without Android experience could weigh in. Specific questions I think need discussing:

- I am terminating the sequence early if the caller does not subscribe using one of the specialized Observer types I provide (`FragmentObserver` or `SupportFragmentObserver` for native and back-compat fragments respectively). As mentioned above, I must force the caller to give me a reference to the fragment, since otherwise callbacks cannot be executed in a safe manner (safe w.r.t. not calling back in case Android decided to remove the fragment from the window; this is a life-cycle event in Android which cannot be intercepted other than asking the fragment whether it's still attached or not). I realize this has a smell to it, but I don't see another option.
- the specialized observer class keeps weak references to the source observer and the fragment (both can be the same object, but then again, could also not if e.g. you use inner classes as observers). In case the references got cleared, messages will be dropped
- Naming: observeInForeground is the best I could come up with, which doesn't mean much :-) Feel free to submit better naming suggestions

TODO:
- Implement native `FragmentObserver` in the same manner as `SupportFragmentObserver` (the latter is what we need so I built that one first)
- Add `ActivityObserver` in the same manner
- Think about auto-unsubscribing from the source sequence in case the references got cleared

[0] https://groups.google.com/forum/?fromgroups=#!topic/rxjava/7o_NJw36Enw