empty observable subscribed, but onNext not called? - system.reactive

I want an Observable that doesnt do anything except that when subscribed to, the observer's onNext callback is invoked. I think I found that with Observable.empty(), but the following does not result in the observer's onNext callback being invoked:
Observable<Void> emptyObservable = Observable.empty();
emptyObservable.subscribe(passedinObserver);
passedInObserver was defined:
Observer<Void> passedinObserver = new Observer<Void> {
#Override public void onCompleted() {
}
#Override public void onError(Throwable e) {
}
#Override public void onNext(Void aVoid) {
Log.d("onNext called");
}
};

You can use Observable.just(null) or any value since you are going to ingore the value anyway. However, it appears you want to perform additional work when values travel through an observable sequence, so you can use doOnNext():
Observable.range(1, 10)
.doOnNext(v -> Log.d("onNext called"))
.map(v -> v * v)
.subscribe(System.out::println);

onNext doesn't get called, onCompleted does for this type of Observable.

Alternatively to the other answers, since empty only calls onCompleted without calling onNext, maybe you just want to do your work in onCompleted rather than in onNext?

Try Observable.just(...). It will return one value and thus call .onNext(...).

Related

I want to implement a custom list method in dart

extension MyMethod on List<int>{
void forEachCustom(void Function(int) other){
for(var e in this){
other(e);
}
}
}
void main(){
List<int> a=[1,2,3,4];
a.forEachCustom(print);
}
This just prints the elements. I want to implement my custom list method that performs operation on the original receiver on which I call the method. Example ,sort() method, that already exists,as it dosent return anything but modifies the list to which we call it
I don't know if I understand your question, but you can easily sort a list in dart with predefined method
extension MyMethod on List<int>{
void forEachCustom(void Function(int) other){
sort();
}
}

RxJava: interval operator is not returning infinite sequence

As per RxJava documentation, interval operator 'create an Observable that emits a sequence of integers spaced by a given time interval'. I written below program, but the subscribe method is not getting called. Am I missed anything here?
Observable<Long> observable = Observable.interval(1, 1, TimeUnit.SECONDS);
observable.subscribe(new Consumer<Long>() {
#Override
public void accept(Long t) throws Exception {
System.out.println(t);
}
});
I am using 'io.reactivex.rxjava2' version 2.2.6
As I explored, Observable data push is happening in daemon thread, to make my application work, I should hold the main thread for some time, so observable has chance to fire the event. I updated the code like below to make the application run.
Observable<Long> observable = Observable.interval(1, 1, TimeUnit.SECONDS);
observable.subscribe(new Consumer<Long>() {
#Override
public void accept(Long t) throws Exception {
//System.out.println(Thread.currentThread().getName() + " " + Thread.currentThread().isDaemon());
System.out.println(t);
}
});
Thread.sleep(5000);

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?

How do I inherit from an Observable<T>?

I want to build an event broker class that inherits from Observable<EventArgs>. In the .NET implementation of Rx, you can simply implement IObservable<EventArgs>; furthermore, in .NET the publish() method just takes the argument that you want the subscribers to receive.
Can someone explain how this is done in Java? All I want is a class who inherently behaves as Observable<Foo>.
In most cases, there is no necessity to implement your own Observable inheritor. There is a bunch of fabrics methods to create Observable and handle it's behavior. For example:
Observable.create(new ObservableOnSubscribe<String>() {
#Override public void subscribe(ObservableEmitter<String> emitter) throws Exception {
emitter.onNext("New event");
emitter.onError(new Error());
emitter.onComplete();
}
});
But, if you really need to create exactly an inheritor it is not difficult either.
class MarkedObservable extends Observable<String> {
#Override protected void subscribeActual(Observer<? super String> observer) {
observer.onNext("Message");
observer.onError(new Error());
observer.onComplete();
}
}

How to intercept the onSuccess() method in GWT

I need to do method interception for the onSuccess method in GWT.
I need to add some code before and after the calling of the onSuccess method in GWT? (I have many calls to the onSuccess method and I need to do this dynamically)
EDIT:
I need to add a progress bar in the right corner of the screen, that appears when the code enters the onsuccess method and disappears on the exit of onsuccess method.
From a visual perspective
void onSuccess(Value v) {
showProgressBar();
doLotsOfWork(v);
hideProgressBar();
}
will be a no-op. Browsers typically wait for event handlers to finish executing before re-rending the DOM. If the doLotsOfWork() method takes a noticeable amount of time to execute (e.g. >100ms) the user will notice the browser hiccup due to the single-threaded nature of JavaScript execution.
Instead, consider using an incrementally-scheduled command to break the work up. It would look roughly like:
void onSuccess(Value v) {
showProgressBar();
Scheduler.get().scheduleIncremental(new RepeatingCommand() {
int count = 0;
int size = v.getElements().size();
public boolean execute() {
if (count == size) {
hideProgressBar();
return false;
}
processOneElement(v.getElements().get(count++));
setProgressBar((double) count / size);
return true;
}
});
}
By breaking the work across multiple pumps of the browser's event loop, you avoid the situation where the webapp becomes non-responsive if there's a non-trivial amount of work to do.
Well, it is a generic non-functional requirement, I have done some research on this item, I have implemented a solution that Thomas Broyer has suggested on gwt group.. This solution has distinct advantage over other suggested solutions, You dont have to change your callback classes, what you have to do is just add a line of code after creation of async gwt-rpc service...
IGwtPersistenceEngineRPCAsync persistenceEngine = GWT.create(IGwtPersistenceEngineRPC.class);
((ServiceDefTarget) persistenceEngine).setRpcRequestBuilder(new ProgressRequestBuilder());
import com.allen_sauer.gwt.log.client.Log;
import com.google.gwt.http.client.Request;
import com.google.gwt.http.client.RequestBuilder;
import com.google.gwt.http.client.RequestCallback;
import com.google.gwt.http.client.Response;
import com.google.gwt.user.client.rpc.RpcRequestBuilder;
public class ProgressRequestBuilder extends RpcRequestBuilder {
private class RequestCallbackWrapper implements RequestCallback {
private RequestCallback callback;
RequestCallbackWrapper(RequestCallback aCallback) {
this.callback = aCallback;
}
#Override
public void onResponseReceived(Request request, Response response) {
Log.debug("onResposenReceived is called");
// put the code to hide your progress bar
callback.onResponseReceived(request, response);
}
#Override
public void onError(Request request, Throwable exception) {
Log.error("onError is called",new Exception(exception));
// put the code to hide your progress bar
callback.onError(request, exception);
}
}
#Override
protected RequestBuilder doCreate(String serviceEntryPoint) {
RequestBuilder rb = super.doCreate(serviceEntryPoint);
// put the code to show your progress bar
return rb;
}
#Override
protected void doFinish(RequestBuilder rb) {
super.doFinish(rb);
rb.setCallback(new RequestCallbackWrapper(rb.getCallback()));
}
}
You cant do that. The rpc onSuccess() method runs asynchronously (in other words, depends on the server when it completes, the app doesnt wait for it). You could fire code immediately after the rpc call which may/ may not complete before the onSuccess for RPC calls.
Can you explain with an eg why exactly do u want to do that? Chances are you might have to redesign the app due to this async behavior, but cant say till you provide a use case. Preferably any Async functionality should be forgotten after the rpc call, and actioned upon only in the onSuccess.