How to create RxJava observables to collect smartphone data inside a service and be subscribed in an activity?
<h2>Context:</h2>

<p>I'm trying to develop an Android application to gather data from many sources such as: battery, hardware, sensors, cell towers, satellites and wifis.</p>

<p>These data has to be "observed" inside a service because I need it to run in background in order to log the data and send it to my server. When the user opens the app I also need to show that data in the activity.</p>

<p>First I wrote my code using many <code>BehaviorSubject</code> singletons, each representing a data source. This way I could pass the data from service using the <code>onNext</code> method and subscribe to it anywhere. But now I want to get rid of <code>Subject</code> objects since it is recommended the usage of <code>Observable</code>.</p>

<hr>

<h2>Problems:</h2>

<p>I have two questions:</p>

<p>Question 1: How to create a RxJava <code>Observable</code> that registers a listener or a <code>BroadcastReceiver</code> at the first subscription and, when all subscribers call the <code>unsubscribe</code> method, it unregisters the listener or receiver?</p>

<p>I have this piece of code to listen to satellites:</p>

<pre><code>private final GpsStatus.Listener gpsListener = new GpsStatus.Listener() {

    GpsStatus gpsStatus = null;

    @Override
    public void onGpsStatusChanged(int event) {
        gpsStatus = locationManager.getGpsStatus(gpsStatus);

        if (event == GpsStatus.GPS_EVENT_SATELLITE_STATUS) {
            if (gpsStatus != null) {
                //put satellite data in some list
            }
        }
    }
};

public registerSatellite() {
    locationManager.addGpsStatusListener(gpsListener);
}

public void unregisterSatellite() {
    locationManager.removeGpsStatusListener(gpsListener);
}
</code></pre>

<p>I also have this piece of code to listen to battery information:</p>

<pre><code>private BroadcastReceiver batteryReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        //put intent data in some variable
    }
};

public registerBattery()
{
    context.registerReceiver(batteryReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
}

public unregisterBattery()
{
    context.unregisterReceiver(batteryReceiver);
}
</code></pre>

<p>Question 2: In order to pass data from service to activity, are singletons a good option?</p>