SubscribeOn main thread - java-8

How can I set the async operator of Observable to run in the main thread instead in another thread. Or at least set to get the result in the main thread once we finish.
#Test
public void retryWhen() {
Scheduler scheduler = Schedulers.newThread();
Single.just("single")
.map(word -> null)
.map(Object::toString)
.retryWhen(ot ->
ot.doOnNext(t -> System.out.println("Retry mechanism:" + t))
.filter(t -> t instanceof NullPointerException && cont < 5)
.flatMap(t -> Observable.timer(100, TimeUnit.MILLISECONDS,scheduler))
.doOnNext(t -> cont++)
.switchIfEmpty(Observable.error(new NullPointerException())))
.subscribeOn(scheduler)
.subscribe(System.out::println, System.out::println);
// new TestSubscriber()
// .awaitTerminalEvent(1000, TimeUnit.MILLISECONDS);
}
I´m trying observerOn and subscribeOn but both are used to set in which thread you want the execution. But in my case I want the execution or the end of it in the same thread where I run the test
Right now the only way to see the prints are just blocking and waiting for the execution.
Regards.

You could use Observable.toBlocking() to get a BlockingObservable and use that to extract your results in your tests.

If you don't specify observeOn/subscribeOn and no operator or Observable changes the thread, then when you subscribe to the observable it will do all the processing during the subscription.

Related

Flux window - gracefully application shutdown

I have flow in my application thath groups request and send them in batch.
Actually it is made with Flux.window operator, and I have question regarding this.
How looks behaviour of window when application going to shut down ?
Should I expect losted pushed events ?
Or If I define timeout on window, then application will wait during window end and then shutdown ?
Or maybe I could define some behaviour of app in such situation.
Thanks for any sugestions.
you can use the Disposable object received on subscribing the flux, to check if the flux window is completed or not.
Disposable subscribe = Flux.just(1, 2, 3)
.map(number -> {
Thread.sleep(1000);
return number;
})
.subscribe();
while (!subscribe.isDisposed() && count < 100) {
Thread.sleep(500);
count++;
System.out.println("Waiting......");
}
System.out.println("disposable:" + subscribe.isDisposed());

dynamics crm 365 plugin delay between execution pipeline stages

Our plugin is running slow on the "Retrieve" message, so I placed a few timestamps in the code to determine where the bottle neck is. I realized there is a 7 second delay which happens intermittently between the end of the pre-operation stage and the start of the post operation stage.
END PRE - 3/22/2018 11:57:55 AM
POST STAGE START - 3/22/2018 11:58:02 AM
protected virtual void RetrievePreOperation()
{
var message = $"END PRE - {DateTime.Now}";
PluginExecutionContext.SharedVariables.Add("message", message);
}
protected virtual void RetrievePostOperation()
{
// Stop recursive calls
if (PluginExecutionContext.Depth > 1) return;
if (PluginExecutionContext.MessageName.ToLower() != Retrieve ||
!PluginExecutionContext.InputParameters.Contains("Target") ||
PluginExecutionContext.Stage != (int)PipelineStages.PostOperation)
return;
var entity = (Entity)PluginExecutionContext.OutputParameters["BusinessEntity"];
string message = PluginExecutionContext.SharedVariables["message"].ToString();
message += $"POST STAGE START - {DateTime.Now}";
}
Any ideas on how to minimize this delay would be appreciated. Thanks
If your plugin step is registered on Asynchronous execution mode, this delay totally depends on Async service load & pipeline of waiting calls/jobs. You can switch it to Synchronous.
If its registered in Synchronous mode but still delay is there intermittently, it depends on many things like which entity, query & complex logic if any.

Call method in parallel with CompletablFuture and ExecutorService

I am trying to make parallel calls to getPrice method, for each product in products. I have this piece of code and verified that getPrice is running in separate threads, but they are running sequentially, not in parallel. Can anyone please point me to what am I missing here?
Thanks a lot for your help.
ExecutorService service = Executors.newFixedThreadPool(THREAD_POOL_SIZE);
Set<Product> decoratedProductSet = products.stream()
.map(product -> CompletableFuture
.supplyAsync(() -> getPrice(product.getId(), date, context), service))
.map(t -> t.exceptionally(throwable -> null))
.map(t -> t.join())
.collect(Collectors.<Product>toSet());
You are streaming your products, sending each of to a CompletableFuture but then wait for it with join, before the stream processes the next one.
Why not use:
products.parallelStream()
.map(p -> getPrice(p.getId(), date, context))
.collect(Collectors.<Product>toSet());

Starting Activity Indicator while Running a database download in a background thread

I am running a database download in a background thread. The threads work fine and I execute group wait before continuing.
The problem I have is that I need to start an activity indicator and it seems that due to the group_wait it gets blocked.
Is there a way to run such heavy process, ensure that all threads get completed while allowing the activity indicator to run?
I start the activity indicator with (I also tried starting the indicator w/o the dispatch_async):
dispatch_async(dispatch_get_main_queue(), {
activityIndicator.startAnimating()
})
After which, I start the thread group:
let group: dispatch_group_t = dispatch_group_create()
let queue: dispatch_queue_t = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0) //also tried QOS_CLASS_BACKGROUND
while iter > 0 {
iter--
dispatch_group_enter(group)
dispatch_group_async(group, queue, {
do {
print("in queue \(iter)")
temp += try query.findObjects()
query.skip += query.limit
} catch let error as NSError {
print("Fetch failed: \(error.localizedDescription)")
}
dispatch_group_leave(group)
})
}
// Wait for all threads to finish and proceed
As I am using Parse, I have modified the code as follows (psuedo code for simplicity):
trigger the activity indicator with startAnimating()
call the function that hits Parse
set an observer in the Parse class on an int to trigger an action when the value reaches 0
get count of new objects in Parse
calculate how many loop iterations I need to pull all the data (using max objects per query = 1000 which is Parse max)
while iterations > 0 {
create a Parse query object
set the query skip value
use query.findObjectsInBackroundWithBlock ({
pull objects and add to a temp array
observer--
)}
iterations--
}
When the observer hits 0, trigger a delegate to return to the caller
Works like a charm.

System does not sleep after restoring the default settings using SetThreadExecutionState

I created a method to prevent the system from sleeping as follows:
public static void KeepSystemAwake(bool bEnable)
{
if (bEnable)
{
EXECUTION_STATE state = SetThreadExecutionState(EXECUTION_STATE.ES_DISPLAY_REQUIRED | EXECUTION_STATE.ES_CONTINUOUS);
}
else
{
EXECUTION_STATE state = SetThreadExecutionState(EXECUTION_STATE.ES_CONTINUOUS);
}
}
The method prevents the system from sleep but when I call the ES_CONTINUOUS part of the method,the system does not sleep at all when I want it behave normally. What am I missing? I'm running this code in a different thread (Timer)
I'm running this code in a different thread (Timer)
If you're using something like a System.Threading.Timer callback, it will be called on different (read: arbitrary) threads.
From MSDN:
The callback method executed by the timer should be reentrant, because it is called on ThreadPool threads
Make sure you're calling SetThreadExecutionState for the same thread. Ideally, you'll serialise calls onto one thread (like the main thread).

Resources