Answer the question
In order to leave comments, you need to log in
Am I creating the Flowable in RxJava3 correctly?
Just started to get acquainted with this framework, and I feel like a monkey with glasses.
In general, I need a Flowable that will create objects and pass them to the observer. The documentation says that the recommended way right now is to use Flowable.create(). As I understand it, this is not the best way, because before executing the listener methods, you need to check whether it is signed.
Flowable<Person> source = Flowable.create(new FlowableOnSubscribe<Person>() {
@Override
public void subscribe(@NonNull FlowableEmitter<Person> emitter) throws Throwable {
for (int i = 0; i < 100000; i++){
try {
Person person = new Person("Name " + i, i);
if (!emitter.isCancelled()) {
emitter.onNext(person);
}
} catch (Throwable t) {
if (! emitter.isCancelled())
emitter.onError(t);
}
}
if (!emitter.isCancelled())
emitter.onComplete();
}
}, BackpressureStrategy.BUFFER)
.subscribeOn(Schedulers.computation());
private static class FSubscriber implements FlowableSubscriber<Person>{
private Subscription subscription;
public void unsubscribe() {
subscription.cancel();
}
@Override
public void onSubscribe(@NonNull Subscription s) {
this.subscription = s;
this.subscription.request(1);
System.out.println("On subs");
}
@Override
public void onNext(Person person) {
System.out.println("On next: " + person.toString());
subscription.request(1);
}
@Override
public void onError(Throwable t) {
System.err.println(t.getMessage());
}
@Override
public void onComplete() {
System.out.println("On complete");
}
};
Answer the question
In order to leave comments, you need to log in
In your case, it's generally better to use Flowable.fromIterable .
If you implement it by hand, checks for cancellation can be omitted. They are under the hood.
About subscribers. You have chosen the most difficult path. Look from here and down. Usually subscribe is used with one or two consumers (onNext and onError respectively). Then you won't have to write all this bunch of code.
As a piece of advice - still drag lambdas, either by taking a newer Java (8+) or use RetroLambda.
Honestly, with anonymous classes, Rx looks like a complete tin, you won’t wish it on your enemy.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question