I have written a subscriber that will get triggered when google map's OnCameraChangeListener
is triggered.
Observable.create(new Observable.OnSubscribe<LatLng>()
{
@Override
public void call(Subscriber<? super LatLng> subscriber)
{
if (!subscriber.isUnsubscribed())
{
mMap.setOnCameraChangeListener(cameraPosition ->
subscriber.onNext(cameraPosition.target));
}
}
}).subscribeOn(AndroidSchedulers.mainThread())
.observeOn(AndroidSchedulers.mainThread())
.onErrorResumeNext(Observable.<LatLng>empty())
.debounce(1, TimeUnit.SECONDS)
.subscribe(position -> {
if (position.latitude != 0 && position.longitude != 0)
{
updateLocationMarker(position);
}
});
I am updating the location marker as below:
private void updateLocationMarker(LatLng center)
{
locationMarkertext.setText("Lat:" + center.latitude + " Long:" + center.longitude);
//locationMarkerLayout.setVisibility(View.VISIBLE);
}
Even though my code says to run on AndroidSchedulers.mainThread()
I get this error:
Caused by: rx.exceptions.OnErrorNotImplementedException: Only the original thread that created a view hierarchy can touch its views.
Can some one please help me understand what is the problem with my approach
User Interface Thread or UI-Thread in Android is a Thread element responsible for updating the layout elements of the application implicitly or explicitly. This means, to update an element or change its attributes in the application layout ie the front-end of the application, one can make use of the UI-Thread.
Caution: A service runs in the main thread of its hosting process; the service does not create its own thread and does not run in a separate process unless you specify otherwise. You should run any blocking operations on a separate thread within the service to avoid Application Not Responding (ANR) errors.
When an application is launched in Android, it creates the first thread of execution, known as the “main” thread. The main thread is responsible for dispatching events to the appropriate user interface widgets as well as communicating with components from the Android UI toolkit.
Android Scheduler — This Scheduler is provided by rxAndroid library. This is used to bring back the execution to the main thread so that UI modification can be made. This is usually used in observeOn method.
The operator debounce
by default runs on the computation scheduler where it will deliver the events flowing through. You have to parameterize it with the main thread scheduler:
.debounce(1, TimeUnit.SECONDS, AndroidSchedulers.mainThread())
In addition, depending on where you create your notification source, you may not need observeOn
and subscribeOn
at all.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With