How implement akka actor in functional style with java - scala

I have simple counter actor implemented in java:
public class CounterJavaActor extends UntypedActor {
int count = 0;
#Override
public void onReceive(Object message) throws Exception {
if (message.equals("incr")) {
count += 1;
} else if (message.equals("get")) {
sender().tell(count, self());
}
}
}
In courses on coursera "Functional reactive programming in scala", I saw functional impementation of counter:
/**
* Advantages:
* state change is explicit
* state is scoped to current behaviour
*/
class CounterScala extends Actor{
def counter(n: Int) : Receive = {
case "incr" => context.become(counter(n+1))
case "get" => sender ! n
}
def receive = counter(0)
}
Upd:
My problem, that in java i can't make recourse functional call like in scala counter(n+1). What it means:
public class CounterJava8Actor extends AbstractActor {
//counter(0) in scala
private PartialFunction<Object, BoxedUnit> counter;
private int n = 0;
public CounterJava8Actor() {
counter =
ReceiveBuilder.
matchEquals("get", s -> {
sender().tell(n, self());
}).
matchEquals("inc", s -> {
//become(counter(n+1) in scala
context().become(counter);
}).build();
receive(counter);
}
}
It is possible to implement it in functional style with java?

According to docs you can use become/unbecome in java 8
http://doc.akka.io/docs/akka/snapshot/java/lambda-actors.html#become-unbecome
here is the sample code copied from there
public class HotSwapActor extends AbstractActor {
private PartialFunction<Object, BoxedUnit> angry;
private PartialFunction<Object, BoxedUnit> happy;
public HotSwapActor() {
angry =
ReceiveBuilder.
matchEquals("foo", s -> {
sender().tell("I am already angry?", self());
}).
matchEquals("bar", s -> {
context().become(happy);
}).build();
happy = ReceiveBuilder.
matchEquals("bar", s -> {
sender().tell("I am already happy :-)", self());
}).
matchEquals("foo", s -> {
context().become(angry);
}).build();
receive(ReceiveBuilder.
matchEquals("foo", s -> {
context().become(angry);
}).
matchEquals("bar", s -> {
context().become(happy);
}).build()
);
}
}
Or you can use UntypedActor like explained in the docs here
http://doc.akka.io/docs/akka/snapshot/java/untyped-actors.html
public class Manager extends UntypedActor {
public static final String SHUTDOWN = "shutdown";
ActorRef worker = getContext().watch(getContext().actorOf(
Props.create(Cruncher.class), "worker"));
public void onReceive(Object message) {
if (message.equals("job")) {
worker.tell("crunch", getSelf());
} else if (message.equals(SHUTDOWN)) {
worker.tell(PoisonPill.getInstance(), getSelf());
getContext().become(shuttingDown);
}
}
Procedure<Object> shuttingDown = new Procedure<Object>() {
#Override
public void apply(Object message) {
if (message.equals("job")) {
getSender().tell("service unavailable, shutting down", getSelf());
} else if (message instanceof Terminated) {
getContext().stop(getSelf());
}
}
};
}
To know how to add parameter to Procedure you can see this answer:
Akka/Java getContext().become with parameter?
and here is actual solution with java 8
private PartialFunction<Object, BoxedUnit> counter(final int n) {
return ReceiveBuilder.
matchEquals("get", s -> {
sender().tell(n, self());
}).
matchEquals("inc", s -> {
context().become(counter(n + 1));
}).build();
}
public CounterJava8Actor() {
receive(counter(0));
}

Related

Is there an equivalent of Project Reactor's Flux.create() that caters for push/pull model in rxjava-2?

Project Reactor has this factory method for creating a push/pull Producer<T>.
http://projectreactor.io/docs/core/release/reference/#_hybrid_push_pull_model
Is there any such thing in RxJava-2?
If not, what would be the recommended way (without actually implemementing reactive specs interfaces from scratch) to create such beast that can handle the push/pull model?
EDIT: as requested I am giving an example of the API I am trying to use...
private static class API
{
CompletableFuture<Void> getT(Consumer<Object> consumer) {}
}
private static class Callback implements Consumer<Object>
{
private API api;
public Callback(API api) { this api = api; }
#Override
public void accept(Object o)
{
//do stuff with o
//...
//request for another o
api.getT(this);
}
}
public void example()
{
API api = new API();
api.getT(new Callback(api)).join();
}
So it's call back based, which will get one item and from within you can request for another one. the completable future flags no more items.
Here is an example of a custom Flowable that turns this particular API into an RxJava source. Note however that in general, the API peculiarities in general may not be possible to capture with a single reactive bridge design:
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.atomic.*;
import java.util.function.*;
import org.reactivestreams.*;
import io.reactivex.Flowable;
import io.reactivex.internal.subscriptions.EmptySubscription;
import io.reactivex.internal.util.BackpressureHelper;
public final class SomeAsyncApiBridge<T> extends Flowable<T> {
final Function<? super Consumer<? super T>,
? extends CompletableFuture<Void>> apiInvoker;
final AtomicBoolean once;
public SomeAsyncApiBridge(Function<? super Consumer<? super T>,
? extends CompletableFuture<Void>> apiInvoker) {
this.apiInvoker = apiInvoker;
this.once = new AtomicBoolean();
}
#Override
protected void subscribeActual(Subscriber<? super T> s) {
if (once.compareAndSet(false, true)) {
SomeAsyncApiBridgeSubscription<T> parent =
new SomeAsyncApiBridgeSubscription<>(s, apiInvoker);
s.onSubscribe(parent);
parent.moveNext();
} else {
EmptySubscription.error(new IllegalStateException(
"Only one Subscriber allowed"), s);
}
}
static final class SomeAsyncApiBridgeSubscription<T>
extends AtomicInteger
implements Subscription, Consumer<T>, BiConsumer<Void, Throwable> {
/** */
private static final long serialVersionUID = 1270592169808316333L;
final Subscriber<? super T> downstream;
final Function<? super Consumer<? super T>,
? extends CompletableFuture<Void>> apiInvoker;
final AtomicInteger wip;
final AtomicLong requested;
final AtomicReference<CompletableFuture<Void>> task;
static final CompletableFuture<Void> TASK_CANCELLED =
CompletableFuture.completedFuture(null);
volatile T item;
volatile boolean done;
Throwable error;
volatile boolean cancelled;
long emitted;
SomeAsyncApiBridgeSubscription(
Subscriber<? super T> downstream,
Function<? super Consumer<? super T>,
? extends CompletableFuture<Void>> apiInvoker) {
this.downstream = downstream;
this.apiInvoker = apiInvoker;
this.requested = new AtomicLong();
this.wip = new AtomicInteger();
this.task = new AtomicReference<>();
}
#Override
public void request(long n) {
BackpressureHelper.add(requested, n);
drain();
}
#Override
public void cancel() {
cancelled = true;
CompletableFuture<Void> curr = task.getAndSet(TASK_CANCELLED);
if (curr != null && curr != TASK_CANCELLED) {
curr.cancel(true);
}
if (getAndIncrement() == 0) {
item = null;
}
}
void moveNext() {
if (wip.getAndIncrement() == 0) {
do {
CompletableFuture<Void> curr = task.get();
if (curr == TASK_CANCELLED) {
return;
}
CompletableFuture<Void> f = apiInvoker.apply(this);
if (task.compareAndSet(curr, f)) {
f.whenComplete(this);
} else {
curr = task.get();
if (curr == TASK_CANCELLED) {
f.cancel(true);
return;
}
}
} while (wip.decrementAndGet() != 0);
}
}
#Override
public void accept(Void t, Throwable u) {
if (u != null) {
error = u;
task.lazySet(TASK_CANCELLED);
}
done = true;
drain();
}
#Override
public void accept(T t) {
item = t;
drain();
}
void drain() {
if (getAndIncrement() != 0) {
return;
}
int missed = 1;
long e = emitted;
for (;;) {
for (;;) {
if (cancelled) {
item = null;
return;
}
boolean d = done;
T v = item;
boolean empty = v == null;
if (d && empty) {
Throwable ex = error;
if (ex == null) {
downstream.onComplete();
} else {
downstream.onError(ex);
}
return;
}
if (empty || e == requested.get()) {
break;
}
item = null;
downstream.onNext(v);
e++;
moveNext();
}
emitted = e;
missed = addAndGet(-missed);
if (missed == 0) {
break;
}
}
}
}
}
Test and example source:
import java.util.concurrent.*;
import java.util.function.Consumer;
import org.junit.Test;
public class SomeAsyncApiBridgeTest {
static final class AsyncRange {
final int max;
int index;
public AsyncRange(int start, int count) {
this.index = start;
this.max = start + count;
}
public CompletableFuture<Void> next(Consumer<? super Integer> consumer) {
int i = index;
if (i == max) {
return CompletableFuture.completedFuture(null);
}
index = i + 1;
CompletableFuture<Void> cf = CompletableFuture
.runAsync(() -> consumer.accept(i));
CompletableFuture<Void> cancel = new CompletableFuture<Void>() {
#Override
public boolean cancel(boolean mayInterruptIfRunning) {
cf.cancel(mayInterruptIfRunning);
return super.cancel(mayInterruptIfRunning);
}
};
return cancel;
}
}
#Test
public void simple() {
AsyncRange r = new AsyncRange(1, 10);
new SomeAsyncApiBridge<Integer>(
consumer -> r.next(consumer)
)
.test()
.awaitDone(500, TimeUnit.SECONDS)
.assertResult(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
}
}
This is something that looks that is working using Reactor's Flux.create(). I changed the API a bit.
public class FlowableGenerate4
{
private static class API
{
private ExecutorService es = Executors.newFixedThreadPool(1);
private CompletableFuture<Void> done = new CompletableFuture<>();
private AtomicInteger stopCounter = new AtomicInteger(10);
public boolean isDone()
{
return done.isDone();
}
public CompletableFuture<Void> getT(Consumer<Object> consumer)
{
es.submit(() -> {
try {
Thread.sleep(100);
} catch (Exception e) {
}
if (stopCounter.decrementAndGet() < 0)
done.complete(null);
else
consumer.accept(new Object());
});
return done;
}
}
private static class Callback implements Consumer<Object>
{
private API api;
private FluxSink<Object> sink;
public Callback(API api, FluxSink<Object> sink)
{
this.api = api;
this.sink = sink;
}
#Override
public void accept(Object o)
{
sink.next(o);
if (sink.requestedFromDownstream() > 0 && !api.isDone())
api.getT(this);
else
sink.currentContext().<AtomicBoolean>get("inProgress")
.set(false);
}
}
private Publisher<Object> reactorPublisher()
{
API api = new API();
return
Flux.create(sink -> {
sink.onRequest(n -> {
//if it's in progress already, do nothing
//I understand that onRequest() can be called asynchronously
//regardless if the previous call demand has been satisfied or not
if (!sink.currentContext().<AtomicBoolean>get("inProgress")
.compareAndSet(false, true))
return;
//else kick off calls to API
api.getT(new Callback(api, sink))
.whenComplete((o, t) -> {
if (t != null)
sink.error(t);
else
sink.complete();
});
});
}).subscriberContext(
Context.empty().put("inProgress", new AtomicBoolean(false)));
}
#Test
public void test()
{
Flowable.fromPublisher(reactorPublisher())
.skip(5)
.take(10)
.blockingSubscribe(
i -> System.out.println("onNext()"),
Throwable::printStackTrace,
() -> System.out.println("onComplete()")
);
}
}

Rx Java 2 pre-pull next item on separate thread

Scenario: I have a stream of data I am reading from the database. What I would like to do is read a chunk of data, process it and stream it using rx-java 2. But while I am processing and streaming it I would like to load the next chunk of data on a separate thread (pre-pull the next chunk).
I have tried:
Flowable.generate(...)
.subscribeOn(Schedulers.io())
.observeOn(Schedulers.computation())
.map(...)
.subscribe(...)
Unfortunately this causes the generate method to continually run on an io thread. I just want one pre-pull. I have tried using buffer, but that really just ends up creating lists of chunks.
So basically while I am streaming the current chunk on a separate thread I want to read the next chunk and have it ready.
Not sure if this is possible. I need to use generate because there is no concept of when the data will end.
I have tried using subscribe(new FlowableSubscriber(){...}) using Subscription::request but that did not seem to work.
There are no standard operators in RxJava that would have this type of request-response pattern. You'd need a custom observeOn that requests before it sends the current item to its downstream.
import java.util.concurrent.atomic.*;
import org.junit.Test;
import org.reactivestreams.*;
import io.reactivex.*;
import io.reactivex.Scheduler.Worker;
import io.reactivex.internal.util.BackpressureHelper;
import io.reactivex.schedulers.Schedulers;
public class LockstepObserveOnTest {
#Test
public void test() {
Flowable.generate(() -> 0, (s, e) -> {
System.out.println("Generating " + s);
Thread.sleep(500);
e.onNext(s);
return s + 1;
})
.subscribeOn(Schedulers.io())
.compose(new LockstepObserveOn<>(Schedulers.computation()))
.map(v -> {
Thread.sleep(250);
System.out.println("Processing " + v);
Thread.sleep(250);
return v;
})
.take(50)
.blockingSubscribe();
}
static final class LockstepObserveOn<T> extends Flowable<T>
implements FlowableTransformer<T, T> {
final Flowable<T> source;
final Scheduler scheduler;
LockstepObserveOn(Scheduler scheduler) {
this(null, scheduler);
}
LockstepObserveOn(Flowable<T> source, Scheduler scheduler) {
this.source = source;
this.scheduler = scheduler;
}
#Override
protected void subscribeActual(Subscriber<? super T> subscriber) {
source.subscribe(new LockstepObserveOnSubscriber<>(
subscriber, scheduler.createWorker()));
}
#Override
public Publisher<T> apply(Flowable<T> upstream) {
return new LockstepObserveOn<>(upstream, scheduler);
}
static final class LockstepObserveOnSubscriber<T>
implements FlowableSubscriber<T>, Subscription, Runnable {
final Subscriber<? super T> actual;
final Worker worker;
final AtomicReference<T> item;
final AtomicLong requested;
final AtomicInteger wip;
Subscription upstream;
volatile boolean cancelled;
volatile boolean done;
Throwable error;
long emitted;
LockstepObserveOnSubscriber(Subscriber<? super T> actual, Worker worker) {
this.actual = actual;
this.worker = worker;
this.item = new AtomicReference<>();
this.requested = new AtomicLong();
this.wip = new AtomicInteger();
}
#Override
public void onSubscribe(Subscription s) {
upstream = s;
actual.onSubscribe(this);
s.request(1);
}
#Override
public void onNext(T t) {
item.lazySet(t);
schedule();
}
#Override
public void onError(Throwable t) {
error = t;
done = true;
schedule();
}
#Override
public void onComplete() {
done = true;
schedule();
}
#Override
public void request(long n) {
BackpressureHelper.add(requested, n);
schedule();
}
#Override
public void cancel() {
cancelled = true;
upstream.cancel();
worker.dispose();
if (wip.getAndIncrement() == 0) {
item.lazySet(null);
}
}
void schedule() {
if (wip.getAndIncrement() == 0) {
worker.schedule(this);
}
}
#Override
public void run() {
int missed = 1;
long e = emitted;
for (;;) {
long r = requested.get();
while (e != r) {
if (cancelled) {
item.lazySet(null);
return;
}
boolean d = done;
T v = item.get();
boolean empty = v == null;
if (d && empty) {
Throwable ex = error;
if (ex == null) {
actual.onComplete();
} else {
actual.onError(ex);
}
worker.dispose();
return;
}
if (empty) {
break;
}
item.lazySet(null);
upstream.request(1);
actual.onNext(v);
e++;
}
if (e == r) {
if (cancelled) {
item.lazySet(null);
return;
}
if (done && item.get() == null) {
Throwable ex = error;
if (ex == null) {
actual.onComplete();
} else {
actual.onError(ex);
}
worker.dispose();
return;
}
}
emitted = e;
missed = wip.addAndGet(-missed);
if (missed == 0) {
break;
}
}
}
}
}
}

xtext parameterized xtext runner

Purpose: Run parameterized tests within xtext/xtend context.
Progress: So far I have achieved getting it to run, but it is appearing wrong in the junit window.
Issues:
The failure trace and results of both tests appear in the last test, as shown in the figure below.
The first test, marked by the red pen, is sort of unresolved and does not contain any failure trace.
Here is the test class:
#RunWith(typeof(Parameterized))
#InjectWith(SemanticAdaptationInjectorProvider)
#Parameterized.UseParametersRunnerFactory(XtextParametersRunnerFactory)
class CgCppAutoTest extends AbstractSemanticAdaptationTest {
new (List<File> files)
{
f = files;
}
#Inject extension ParseHelper<SemanticAdaptation>
#Inject extension ValidationTestHelper
#Parameters(name = "{index}")
def static Collection<Object[]> data() {
val files = new ArrayList<List<File>>();
listf("test_input", files);
val test = new ArrayList();
test.add(files.get(0));
return Arrays.asList(test.toArray(), test.toArray());
}
def static void listf(String directoryName, List<List<File>> files) {
...
}
var List<File> f;
#Test def allSemanticAdaptations() {
System.out.println("fail");
assertTrue(false);
}
}
ParameterizedXtextRunner (Inspiration from here: https://www.eclipse.org/forums/index.php?t=msg&th=1075706&goto=1726802&):
class ParameterizedXtextRunner extends XtextRunner {
val Object[] parameters;
val String annotatedName;
new(TestWithParameters test) throws InitializationError {
super(test.testClass.javaClass)
parameters = test.parameters;
annotatedName = test.name;
}
override protected getName() {
return super.name + annotatedName;
}
override protected createTest() throws Exception {
val object = testClass.onlyConstructor.newInstance(parameters)
val injectorProvider = getOrCreateInjectorProvider
if (injectorProvider != null) {
val injector = injectorProvider.injector
if (injector != null)
injector.injectMembers(object)
}
return object;
}
override protected void validateConstructor(List<Throwable> errors) {
validateOnlyOneConstructor(errors)
}
And finally XtextParametersRunnerFactory:
class XtextParametersRunnerFactory implements ParametersRunnerFactory {
override createRunnerForTestWithParameters(TestWithParameters test) throws InitializationError {
new ParameterizedXtextRunner(test)
}
}
By looking at the XtextRunner class it inherits from BlockJUnit4ClassRunner.
Parameterized does not extend this runner, but
ParentRunner. However, so does BlockJUnit4ClassRunner
Therefore we implemented it as below:
public class XtextParametersRunnerFactory implements ParametersRunnerFactory {
#Override
public Runner createRunnerForTestWithParameters(TestWithParameters test) throws InitializationError {
return new XtextRunnerWithParameters(test);
}
}
And used the code from XtextRunner and put it into the new runner -- it is necessary to extract InjectorProviders from Xtext as well
public class XtextRunnerWithParameters extends BlockJUnit4ClassRunnerWithParameters {
public XtextRunnerWithParameters(TestWithParameters test) throws InitializationError {
super(test);
}
#Override
public Object createTest() throws Exception {
Object object = super.createTest();
IInjectorProvider injectorProvider = getOrCreateInjectorProvider();
if (injectorProvider != null) {
Injector injector = injectorProvider.getInjector();
if (injector != null)
injector.injectMembers(object);
}
return object;
}
#Override
protected Statement methodBlock(FrameworkMethod method) {
IInjectorProvider injectorProvider = getOrCreateInjectorProvider();
if (injectorProvider instanceof IRegistryConfigurator) {
final IRegistryConfigurator registryConfigurator = (IRegistryConfigurator) injectorProvider;
registryConfigurator.setupRegistry();
final Statement methodBlock = superMethodBlock(method);
return new Statement() {
#Override
public void evaluate() throws Throwable {
try {
methodBlock.evaluate();
} finally {
registryConfigurator.restoreRegistry();
}
}
};
}else{
return superMethodBlock(method);
}
}
protected Statement superMethodBlock(FrameworkMethod method) {
return super.methodBlock(method);
}
protected IInjectorProvider getOrCreateInjectorProvider() {
return InjectorProviders.getOrCreateInjectorProvider(getTestClass());
}
protected IInjectorProvider getInjectorProvider() {
return InjectorProviders.getInjectorProvider(getTestClass());
}
protected IInjectorProvider createInjectorProvider() {
return InjectorProviders.createInjectorProvider(getTestClass());
}
}
Creating a test:
#RunWith(typeof(Parameterized))
#InjectWith(SemanticAdaptationInjectorProvider)
#Parameterized.UseParametersRunnerFactory(XtextParametersRunnerFactory)
class xxx
{
#Inject extension ParseHelper<SemanticAdaptation>
#Inject extension ValidationTestHelper
// Here goes standard parameterized stuff
}
due to OSGi import package constraits and deprecation I use this adoption of the original code:
package de.uni_leipzig.pkr.handparser.tests.runners;
import org.eclipse.xtext.testing.IInjectorProvider;
import org.eclipse.xtext.testing.IRegistryConfigurator;
import org.eclipse.xtext.testing.XtextRunner;
import org.junit.runners.model.FrameworkMethod;
import org.junit.runners.model.InitializationError;
import org.junit.runners.model.Statement;
import org.junit.runners.parameterized.BlockJUnit4ClassRunnerWithParameters;
import org.junit.runners.parameterized.TestWithParameters;
import com.google.inject.Injector;
public class XtextRunnerWithParameters extends BlockJUnit4ClassRunnerWithParameters {
public static class MyXtextRunner extends XtextRunner {
public MyXtextRunner(Class<?> testClass) throws InitializationError {
super(testClass);
}
public IInjectorProvider getOrCreateInjectorProvider() {
return super.getOrCreateInjectorProvider();
}
}
private MyXtextRunner xtextRunner;
public XtextRunnerWithParameters(TestWithParameters test) throws InitializationError {
super(test);
xtextRunner = new MyXtextRunner(test.getTestClass().getJavaClass());
}
#Override
public Object createTest() throws Exception {
Object object = super.createTest();
IInjectorProvider injectorProvider = xtextRunner.getOrCreateInjectorProvider();
if (injectorProvider != null) {
Injector injector = injectorProvider.getInjector();
if (injector != null)
injector.injectMembers(object);
}
return object;
}
#Override
protected Statement methodBlock(FrameworkMethod method) {
IInjectorProvider injectorProvider = xtextRunner.getOrCreateInjectorProvider();
if (injectorProvider instanceof IRegistryConfigurator) {
final IRegistryConfigurator registryConfigurator = (IRegistryConfigurator) injectorProvider;
registryConfigurator.setupRegistry();
final Statement methodBlock = superMethodBlock(method);
return new Statement() {
#Override
public void evaluate() throws Throwable {
try {
methodBlock.evaluate();
} finally {
registryConfigurator.restoreRegistry();
}
}
};
} else {
return superMethodBlock(method);
}
}
protected Statement superMethodBlock(FrameworkMethod method) {
return super.methodBlock(method);
}
}

RxJava 2.x: serialize() doesn't work

I tried below to test the sereialize().
I called onNext 1,000,000 times to count from 2 different threads.
Then, I expected to get 2,000,000 at onComplete.
However, I couldn't get the expected value.
private static int count = 0;
private static void setCount(int value) {
count = value;
}
private static final int TEST_LOOP = 10;
private static final int NEXT_LOOP = 1_000_000;
#Test
public void test() throws Exception {
for (int test = 0; test < TEST_LOOP; test++) {
Flowable.create(emitter -> {
ExecutorService service = Executors.newCachedThreadPool();
emitter.setCancellable(() -> service.shutdown());
Future<Boolean> future1 = service.submit(() -> {
for (int i = 0; i < NEXT_LOOP; i++) {
emitter.onNext(i);
}
return true;
});
Future<Boolean> future2 = service.submit(() -> {
for (int i = 0; i < NEXT_LOOP; i++) {
emitter.onNext(i);
}
return true;
});
if (future1.get(1, TimeUnit.SECONDS)
&& future2.get(1, TimeUnit.SECONDS)) {
emitter.onComplete();
}
}, BackpressureStrategy.BUFFER)
.serialize()
.cast(Integer.class)
.subscribe(new Subscriber<Integer>() {
private int count = 0;
#Override
public void onSubscribe(Subscription s) {
s.request(Long.MAX_VALUE);
}
#Override
public void onNext(Integer t) {
count++;
}
#Override
public void onError(Throwable t) {
fail(t.getMessage());
}
#Override
public void onComplete() {
setCount(count);
}
});
assertThat(count, is(NEXT_LOOP * 2));
}
}
I wonder whether serialize() doesn't work or I missunderstood the usage of serialize()
I checked the source of SerializedSubscriber.
#Override
public void onNext(T t) {
...
synchronized(this){
...
}
actual.onNext(t);
emitLoop();
}
Since actual.onNext(t); is called out of synchronized block, I guess that actual.onNext(t); could be called from different threads at the same time. Also, it may be possible to call onComplete before onNext would be done, I guess.
I used RxJava 2.0.4.
This is not a bug but a misuse of the FlowableEmitter:
The onNext, onError and onComplete methods should be called in a sequential manner, just like the Subscriber's methods. Use serialize() if you want to ensure this. The other methods are thread-safe.
FlowableEmitter.serialize()
Applying Flowable.serialize() is too late for the create operator.

Netbeans QuickSearch Result to Lookup

Well, I'd like to provide QuickSearch result inside application, and, of course, through the lookup.
Searching works well, but found result is not visible through global lookup.
Can someone help to overcome this issue ?
Here is th code for a quicksearch :
public class QSERSCompany implements SearchProvider {
#Override
public void evaluate(SearchRequest request, SearchResponse response) {
try {
for (Company k : queries.ERSQuery.allCompanies()) {
if (k.getCompanyName().toLowerCase().contains(request.getText().toLowerCase())) {
if (!response.addResult(new SearchResult(k), k.getCompanyName())) {
return;
}
}
}
} catch (NullPointerException npe) {
}
}
private static class SearchResult implements Runnable, Lookup.Provider {
private final Company company;
private final InstanceContent ic = new InstanceContent();
private final Lookup lookup = new AbstractLookup(ic);
public SearchResult(Company c) {
this.company= c;
}
#Override
public void run() {
ic.add(company);
try {
StatusDisplayer.getDefault().setStatusText(
company.getCompanyName()
+ ", " + company.getAddress()
+ ", " + company.getCity());
} catch (NullPointerException npe) {
}
}
#Override
public Lookup getLookup() {
return lookup;
}
}
}
And this is partof the code which listens for a Company object :
public final class ManagementPodatakaTopComponent extends TopComponent {
private Lookup.Result<Company> companyLookup = null;
...
private Company selectedCompany;
...
#Override
public void componentOpened() {
companyLookup = Utilities.actionsGlobalContext().lookupResult(Company.class);
companyLookup .addLookupListener(new LookupListener() {
#Override
public void resultChanged(LookupEvent le) {
Lookup.Result k = (Lookup.Result) le.getSource();
Collection<Company> cs = k.allInstances();
for (Company k1 : cs) {
selectedCompany = k1;
}
setCompanyTextFields(selectedCompany);
jTP_DataManagement.setVisible(true);
jPanel_Entiteti.setVisible(true);
}
});
}
A SearchResult which provides a lookup? Never seen this in the wild.
Please ask at nbdev#netbeans.org to get better feedback (probably from one of the NB devs)
I finally managed somehow to get what I want :
First off, define interface:
public interface ICodes {
public Code getCode();
}
Then, we implement quick search :
#ServiceProvider(service = ICodes.class)
public class ClientServicesQS implements SearchProvider, ICodes {
private static Code code = null;
#Override
public void evaluate(SearchRequest request, SearchResponse response) {
try {
for (Code c : INFSYS.queries.INFSistemQuery.ByersByName(request.getText())) {
if (!response.addResult(new SearchResult(c),
c.getName() + " ,Code: " + c.getByerCode()
+ (c.getAddress() != null ? ", " + c.getAddress() : ""))) {
return;
}
}
} catch (NullPointerException npe) {
StatusDisplayer.getDefault().setStatusText("Error." + npe.getMessage());
}
}
#Override
public Code getCode() {
return ClientServicesQS.sifra;
}
private static class SearchResult implements Runnable {
private final Code code;
public SearchResult(Code code) {
this.code= code;
}
#Override
public void run() {
try {
ClientServicesQS.code= this.code;
OpenTopComponent("ClientServicesTopComponent");
} catch (NullPointerException e) {
Display.messageBaloon("Error.", e.toString() + ", " + e.getMessage(), Display.TYPE_MESSAGE.ERROR);
}
}
}
}
Finally, we implement lookup in other module through platform.
Because I want to call lookup whenever componentOpen, oe componentActivated is invoked, it is usefull first to define :
private void QSCodeSearch() {
try {
ICode ic= Lookup.getDefault().lookup(ICode.class);
if ((code = ic.getCode()) != null) {
.
.
.
// setup UI components with data from lookup
.
.
.
}
} catch (Exception e) {
}
}
And when topcomponent is activated, we call QSCodeSearch() in :
#Override
public void componentOpened() {
...
QSCodeSearch()
...
}
...
#Override
public void requestActive() {
...
QSCodeSearch()
...
}