SingleObserver.onError called on background thread instead of main thread - rx-java2

Well as I understood from the documentation using singel.observeOn(Scheduler) will guarantee that any downstream event will be executed on that scheduler.
Apparently the onError called on the same scheduler that thrown the error as I receiving this error -
> Caused by:java.lang.IllegalStateException: Cannot invoke setValue on a background thread
at androidx.lifecycle.LiveData.assertMainThread(LiveData.java:443)
at androidx.lifecycle.LiveData.setValue(LiveData.java:286)
at androidx.lifecycle.MutableLiveData.setValue(MutableLiveData.java:33)
at com.bonimoo.womlauncher.presentation.wizard.registration.RegistrationViewModel$1.onError(RegistrationViewModel.java:89)
at io.reactivex.internal.operators.single.SingleFlatMap$SingleFlatMapCallback$FlatMapSingleObserver.onError(SingleFlatMap.java:116)
at io.reactivex.internal.observers.ResumeSingleObserver.onError(ResumeSingleObserver.java:51)
at io.reactivex.internal.disposables.EmptyDisposable.error(EmptyDisposable.java:78)
at io.reactivex.internal.operators.single.SingleError.subscribeActual(SingleError.java:42)
at io.reactivex.Single.subscribe(Single.java:3603)
out of this code -
public static<T> SingleTransformer<T,T> getSingleTransformer(){
return upstream -> upstream
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread());
}
GetHotelsList getHotelsList = new GetHotelsList(
AsyncTransformers.getSingleTransformer(), networkRepo);
getHotelsList.getHotels()
.map(hotels->
CollectionsUtil.mapList(hotels,
RegistrationMappers::mapHotelToPresentationHotel)
)
.flatMap((Function<List<HotelPresentation>, SingleSource<List<HotelPresentation>>>) hotelPresentations ->
Completable.timer(5,TimeUnit.SECONDS, Schedulers.io())
.andThen(Single.error(new Throwable()))
)
.subscribe(new SingleObserver<List<HotelPresentation>>() {
#Override
public void onSubscribe(Disposable d) {
addDisposable(d);
RegistrationState currentState = stateLiveData.getValue();
stateLiveData.setValue(currentState.newBuilder().setLoadingHotels(true).build());
}
#Override
public void onSuccess(List<HotelPresentation> hotelPresentations) {
RegistrationState currentState = stateLiveData.getValue();
stateLiveData.setValue(currentState.newBuilder().setHotelsList(hotelPresentations).setLoadingHotels(false).build());
}
#Override
public void onError(Throwable e) {
RegistrationState currentState = stateLiveData.getValue();
stateLiveData.setValue(currentState.newBuilder().setLoadingHotels(false).build());
}
});
and the debugger shown that onError called on RxSchedulerIoThread.

Related

Android Room with RXJava2; onNext() of emitter is not properly triggered

I am switching from async tasks to rxjava2 and have some issues with my code tests.
I have a room table of elements that have a certain monetary amount. On a usercontrol that is called DisplayCurrentBudget, a sum of all amounts should be displayed. This number must refresh everytime a new element is inserted. I tackled the requirement in two ways, but both produce the same result: My code does not care if the database is updated, it only updates when the fragment is recreated (onCreateView).
My first attempt was this:
//RxJava2 Test
Observable<ItemS> ItemObservable = Observable.create( emitter -> {
try {
List<ItemS> movies = oStandardModel.getItemsVanilla();
for (ItemS movie : movies) {
emitter.onNext(movie);
}
emitter.onComplete();
} catch (Exception e) {
emitter.onError(e);
}
});
DisposableObserver<ItemS> disposable = ItemObservable.
subscribeOn(Schedulers.io()).
observeOn(AndroidSchedulers.mainThread()).
subscribeWith(new DisposableObserver<ItemS>() {
public List<ItemS> BadFeelingAboutThis = new ArrayList<ItemS>();
#Override
public void onNext(ItemS movie) {
// Access your Movie object here
BadFeelingAboutThis.add(movie);
}
#Override
public void onError(Throwable e) {
// Show the user that an error has occurred
}
#Override
public void onComplete() {
// Show the user that the operation is complete
oBinding.DisplayCurrentBudget.setText(Manager.GetBigSum(BadFeelingAboutThis).toString());
}
});
I already was uncomfortable with that code. My second attempt produces the exact same result:
Observable<BigDecimal> ItemObservable2 = Observable.create( emitter -> {
try {
BigDecimal mySum = oStandardModel.getWholeBudget();
emitter.onNext(mySum);
emitter.onComplete();
} catch (Exception e) {
emitter.onError(e);
}
});
DisposableObserver<BigDecimal> disposable = ItemObservable2.
subscribeOn(Schedulers.io()).
observeOn(AndroidSchedulers.mainThread()).
subscribeWith(new DisposableObserver<BigDecimal>() {
#Override
public void onNext(BigDecimal sum) {
// Access your Movie object here
oBinding.DisplayCurrentBudget.setText(sum.toString());
}
#Override
public void onError(Throwable e) {
// Show the user that an error has occurred
}
#Override
public void onComplete() {
// Show the user that the operation is complete
}
});
Any obvious issues with my code?
Thanks for reading, much appreciate it!
Edit:
I was asked what Manager.GetBigSum does, it actually does not do much. It only adds BigDecimal-Values of an Item list.
public static BigDecimal GetBigSum(List<ItemS> ListP){
List<BigDecimal> bigDList = ListP.stream().map(ItemS::get_dAmount).collect(Collectors.toList());
return bigDList.stream()
.reduce(BigDecimal.ZERO, BigDecimal::add);
}
Further, I simplified the query. But it still does not care about DB updates, only about fragment recreation:
Single.fromCallable(() -> oStandardModel.getItemsVanilla())
.map(Manager::GetBigSum)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
e -> oBinding.DisplayCurrentBudget.setText(e.toString())
);
Your rx logic has no error. That should be internal error in your getWholeBudget.
But why you write rx so complex?
For your case, you can just write:
Single.fromCallable(() -> oStandardModel.getItemsVanilla())
.map(Manager::GetBigSum)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
e -> oBinding.DisplayCurrentBudget.setText(sum.toString()),
e -> log.error(e));
I solved it this way:
oStandardModel.getItemJointCatLive().observe(this, new Observer<List<ItemJointCat>>() {
#Override
public void onChanged(#Nullable final List<ItemJointCat> oItemSP) {
Single.fromCallable(() -> oStandardModel.getWholeBudget())
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
e -> oBinding.DisplayCurrentBudget.setText(e.toString())
);
}
});
My mistake was that I assumed RXjava2 does not need an onchanged event...now i just use onchanged event of livedata observer to trigger a simple rxjava2 query.
Do you think there is anything wrong with that approach?

Vert.x: Verticle custom startFuture handler is always rewritten

Vert.x v3.5.1.
There is my custom start method of Verticle:
#Override
public void start(Future<Void> startFuture) throws Exception {
startFuture.setHandler(event -> {
if (event.succeeded()) {
logger.info("Server started on port: {}", 8080);
} else {
logger.warn("Failed to start: {}", event.cause());
}
});
vertx.createHttpServer()
.requestHandler(router()::accept)
.listen(8080, event -> {
if (event.succeeded()) {
startFuture.complete();
} else {
startFuture.fail(event.cause());
}
});
}
I expect that my custom handler will be invoked when future completes. But it doesn't!
In debug mode I see that FutureImpl::setHandler is called twice: once with my custom handler, and then with DeploymentManager's handler during doDeploy.
So the latest handler is applied.
The question is: is it possible to specify custom callback for Verticle start? If yes how can I do it?
Thank you in advance.
You're not supposed to change the handler of the startFuture, as it is owned by the caller. So simply, don't do that :) The future is used to signal that you're done with your start-code, and not to define what should be done, once you're done.
In your concrete example it'd be better to write the logs once the http server came up, and then indicate to the startFuture, that you're done with your code execution.
#Override
public void start(Future<Void> startFuture) throws Exception {
vertx.createHttpServer()
.requestHandler(router()::accept)
.listen(8080, event -> {
if (event.succeeded()) {
logger.info("Server started on port: {}", 8080);
startFuture.complete();
} else {
logger.warn("Failed to start: {}", event.cause());
startFuture.fail(event.cause());
}
});
}
At first, write your verticle as a AbstractVerticle extension. And do not override start(Future) method. Instead use start() method. It will be called from AbstractVerticle.start(Future), and you can specify that future in Vertx.deployVerticle(verticle, options, future) method.
For example:
You have some verticle. Do in it start() method only initialization tasks:
#Override
public void start() throws Exception {
vertx.eventbus().consume(address, m -> {
// consumer code skipped
});
}
and verticle registration:
final DeploymentOptions opts = new DeploymentOptions().setWorker(true);
vertx.deployVerticle(verticle, opts, event -> {
if (event.succeeded()) {
log.info("Verticle successfully deployed. DeploymentId: " + event.result());
} else {
log.error("Verticle failed to deploy. Cause: " + event.cause().getMessage(), event.cause());
}
});
That's all :)

onStartJob is not getting called, except onCreate() in JobService Class

onStartJob is not getting called at all, but onCreate of JobService Geting called, can someone suggest me, what's the reason.
the code prototype is here->
public class SyncToDB extends JobService {
private static final String TAG = "SyncService";
#Override
public boolean onStartJob(JobParameters params) {
Log.i(TAG, "on start job: " + params.getJobId());
return true;
}
#Override
public boolean onStopJob(JobParameters params) {
return true;
}
}

When is it necessary to check if a subscriber is subscribed prior to calling onNext() and onError()?

Consider the following example, it creates an Observable that wraps another API that produces Widgets
public Observable<Widget> createWidgetObservable() {
return Observable.create(new Observable.OnSubscribe<Widget>() {
#Override
public void call(final Subscriber<? super Widget> subscriber) {
WidgetCreator widgetCreator = new WidgetCreator();
widgetCreator.setWidgetCreatorObserver(new WidgetCreator.WidgetCreatorObserver() {
#Override
public void onWidgetCreated(Widget widget) {
if (!subscriber.isUnsubscribed()) {
subscriber.onNext(widget);
}
}
#Override
public void onWidgetError(Throwable e) {
if (!subscriber.isUnsubscribed()) {
subscriber.onError(e);
}
}
});
}
});
}
Are the subscriber.isUnsubscribed() checks necessary prior to calling subscriber.onNext() and subscriber.onError()?
If so, are the checks always necessary or does it depend on the composition / subscriber that's using the observable?
Is it best practice to include the checks?
You can use them to narrow the window between an emission and an unsubscription but if you don't have loops, it is unnecessary most of the time. The more important thing is that if an unsubscription happen, you'd have to "unset" the WidgetCreatorObserver otherwise it will keep receiving and dropping data and keeping alive every reference it may hold.
WidgetCreator widgetCreator = new WidgetCreator();
WidgetCreator.WidgetCreatorObserver wo = new WidgetCreator.WidgetCreatorObserver() {
#Override
public void onWidgetCreated(Widget widget) {
if (!subscriber.isUnsubscribed()) {
subscriber.onNext(widget);
}
}
#Override
public void onWidgetError(Throwable e) {
if (!subscriber.isUnsubscribed()) {
subscriber.onError(e);
}
}
}
widgetCreator.setWidgetCreatorObserver(wo);
wo.add(Subscriptions.create(() -> widgetCreator.removeWidgetCreatorObserver(wo)));

Postsharp Aspect with Async methods

I'm using Trial Ultimate version of PostSharp 4.0 but this doesn't work for me. Can you please check my code and advise. The error doesn't gets logged. And if i put the breakpoint doesn't hit onException method
This is code that I've written for Error handling Aspect
[Serializable]
public class MyMethodAspectAttribute : OnMethodBoundaryAspect
{
public MyMethodAspectAttribute()
{
this.ApplyToStateMachine = true;
}
public override void OnEntry(MethodExecutionArgs args)
{
Console.Write("Method Entry");
}
public override void OnException(MethodExecutionArgs args)
{
Console.Write(args.Exception.Message);
args.ReturnValue = null;
args.FlowBehavior = FlowBehavior.Return;
}
}
This is class where I've implemented this aspect
public class ErrorMethods
{
[MyMethodAspect]
public Task<int> Calculate(int i, int j)
{
var task = Task.Factory.StartNew(
() => i / j);
return task;
}
}
This is how I've used this method
private async void Button_Click(object sender, RoutedEventArgs e)
{
var obj = new ErrorMethods();
var result = await obj.Calculate(1, 0);
if (null == result)
{
MessageBox.Show("error");
}
}
The Calculate method in your example is not an async method, so setting ApplyToStateMachine aspect's property doesn't have effect on this method. The exception is thrown when a newly created task executes in the background and the aspect has no chance of catching it.
If you change your Calculate method to async method, then the async state machine execution can be intercepted by the aspect and OnException handler is invoked upon exception.
Note, however that setting the ReturnValue and FlowBehavior does not alter the flow of the state machine, so the exception will not be swallowed.
public class ErrorMethods
{
[MyMethodAspect]
public async Task<int> Calculate( int i, int j )
{
return await Task.Factory.StartNew( () => i / j );
}
}