RxJava/RxScala async code inside Observer.onNext - asynchronous

Let's assume that you want to store events from some stream into the database and a client library to that database is asynchronous.
E.g. there is a method writeEvent(event: MyEvent): Future[Boolean] that you have to call inside onNext of your observer when the next event is emitted. Is there a good way to do this otherwise than blocking on the Future?
The only way that I currently see on how to implement this, is to create some custom Scheduler that allows me to return thread to the pool, until async code inside onNext is complete.

You do not want to block like that inside your onNext subscriber callback, that would defeat Rx. It can be chained together in a more idiomatic way.
I don't work with Futures much, but I wonder if Observable.from(Future) would work:
someStream
.flatMap(evt => Observable.from(writeEvent(evt)))
.subscribe(
next => ...,
err => ...
)

Related

Wait for resolving Observable for synchronous usage

I like to resolve my Observable res$ before continue with log-ready. But I found no way, to achieve that. I can't move my last log-line into async context. Is there a way to solve that problem?
let o1 = Observable.create((o) => {
console.log('o1 start');
setTimeout(() => {
console.log(`o1 is running`);
o.next('o1');
}, 1500);
console.log('o1 ends');
});
let o2 = Observable.create((o) => {
console.log('o2 starts');
setTimeout(() => {
console.log(`o2 is running`);
o.next('o2');
}, 1100);
console.log('o2 ends');
});
let res$ = o1.pipe(concatMap(() => o2)).subscribe();
//ToDO resolve res$ before continue execution
console.log(`ready`);
https://stackblitz.com/edit/rxjs-b9z3wn?devtoolsheight=60
Is there a way to solve that problem?
In short: No, this is impossible.
JavaScript is a single-theaded language. Asynchronous code is all run on the same thread such that two parts of your JavaScript code will never run at the same time.
This has some advantages. For example, you rarely need to worry about mutex's, semaphores, etc. With JavaScript you can be certain that all synchronous code will run to completion before any other code is run.
There is a downside, however, it's not possible to lift an asynchronous context into a synchronous one. Any attempt to do so will never halt (the way a program fails when you write an infinite loop). This is why Node.js was (still is for older code) infamous for callback hell. It relies heavily on shoving callbacks onto the event loop since it is never allowed to wait. Promises and Observables are two ways to manage this complexity.
JavaScript is single threaded. So if you wait for 10 seconds, the whole program will hang for 10 seconds and do nothing. If you try to wait for something else to happen, the single thread will be busy waiting for forever and therefore be too busy to go do the thing it's waiting for.
You can convert an Observable to a Promise and await it afterwards. Try this:
await o1.pipe(concatMap(() => o2)).toPromise()

Why Future works after the main function was done?

In the example on dart.dev the Future prints the message after the main function was done.
Why might the Future work after the main function was done? At first glance, after the completion of the main function, the entire work of the program is expected to be completed (and the Future must be cancelled).
The example code:
Future<void> fetchUserOrder() {
// Imagine that this function is fetching user info from another service or database.
return Future.delayed(Duration(seconds: 2), () => print('Large Latte'));
}
void main() {
fetchUserOrder();
print('Fetching user order...');
}
The program prints
Fetching user order...
Large Latte
I've expected just the following
Fetching user order...
This has to do with the nature of futures and asynchronous programming. Behind the scenes, Dart manages something called the asynchronous queue. When you initiate a future (either manually like you did with Future.delayed or implicitly by calling a method marked async, that function's execution goes into the queue whenever its execution gets deferred. Every cycle when Dart's main thread is idle, it checks the futures in the queue to see if any of them are no longer blocked, and if so, it resumes their execution.
A Dart program will not terminate while futures are in the queue. It will wait for all of them to either complete or error out.

Return a Promise from Redux Observable

Maybe I'm thinking about this wrong, but a common pattern I use with redux-thunk is to return a promise so I can perform some additional actions in the container object when something completes or fails.
Using Thunk as an example:
Action Creator:
const action = ({ data }) => (dispatch) =>
fetch(`some http url`)
.then(response => {
if(response.ok) {
return response.json();
}
return Promise.reject(response);
})
Somewhere in the connected component:
this.props.action("Some Data")
.then(console.log)
.catch(error => console.error("ERROR"));
Is there a clean way of doing something similar in Redux-Observable/Rxjs? Basically returning a promise from an action, calling an epic, that returns resolve or reject once the observable is complete.
Generally speaking, I try to shy people away from these patterns when using things like redux-observable/redux-saga. Instead, if you're waiting for an action you dispatched to update the store's state, rely on that state update itself or some sort of transactional metadata your reducers store in the state about it. e.g. { transactions: { "123": { isPending: true, error: null } }
However, if you really do want to do it, you can write (or use an existing) middleware that returns a Promise from dispatch that will resolve when some other specified action has been dispatched (presumably by your epics). redux-wait-for-action is one example (not a recommendation, though cause I haven't used any)
Keep in mind that Promises are not normally cancellable, so you could accidentally create a situation where a component starts waiting for an action, the user leaves that page and the component is unmounted, and you're still waiting for that other action--which can cause weirdness later, like if they come back to that page, etc.
If you're waiting to chain side effects, that belongs in your epics. Kick off a single action that an epic listens for, makes the side effect, then it emits another action to signal completion. Another epic listens for that completion action and then begins the other side effect, etc. You could put them all in a single monolithic epic, if you want, but I find the separation easier for testing and reuse.

SignalR .Net client - how to invoke synchronously and asynchronously

I'm learning SignalR using the .Net client (not javascript), and was hoping for some clarification on how to invoke hub proxy methods in a synchronous or asynchronous manner.
Method with no return value
So far I've been doing something like this:-
myHubProxy.Invoke("DoSomething");
I've found this to be asynchronous, which is fine as it's effectively "fire-and-forget" and doesn't need to wait for a return value. A couple of questions though:-
Are there any implications with wrapping the Invoke in a try..catch block, particularly with it being asynchronous? I might want to know if the call failed.
Are there any scenarios where you would want to call a method that doesn't return a value synchronously? I've seen the .Wait() method mentioned, but I can't think why you would want to do this.
Method with return value
So far I've been using the Result property, e.g.:-
var returnValue = myHubProxy.Invoke<string>("DoSomething").Result;
Console.WriteLine(returnValue);
I'm assuming this works synchronously - after all, it couldn't proceed to the next line until a result had been returned. But how do I invoke such a method asynchronously? Is it possible to specify a callback method, or should I really be using async/await these days (something I confess to still not learning about)?
If you want to write asynchronous code, then you should use async/await. I have an intro on my blog with a number of followup resources at the end.
When you start an asynchronous operation (e.g., Invoke), then you get a task back. The Task type is used for asynchronous operations without a return value, and Task<T> is used for asynchronous operations with a return value. These task types can indicate to your code when the operation completes and whether it completed successfully or with error.
Although you can use Task.Wait and Task<T>.Result, I don't recommend them. For one, they wrap any exceptions in an AggregateException, which make your error handling code more cumbersome. It's far easier to use await, which does not do this wrapping. Similarly, you can register a callback using ContinueWith, but I don't recommend it; you need to understand a lot about task schedulers and whatnot to use it correctly. It's far easier to use await, which does the (most likely) correct thing by default.
The .Result property returns a async Task, so the server requests is still performed async.
There is not reason to hold up a thread for the duration of the call thats why you use async.
If you fire the call on the GUI thread its even more important todo it async because otherwise the GUI will not respond while the call is done
1) Yuo need to use the await keyword if you want try catch blocks to actually catch server faults. Like
try
{
var foo = await proxy.Invoke<string>("Bar");
}
catch (Exception ex)
{
//act on error
}
2) I think you ment to ask if its any reason to call it async? And yes like I said, you do not want to block any threads while the request is being made

AS3 - How to do a synchronous load of an asynchronous call?

I have a function that loads a user object from a web service asynchronously.
I wrap this function call in another function and make it synchronous.
For example:
private function getUser():User{
var newUser:User;
var f:UserFactory = new UserFactory();
f.GetCurrent(function(u:User):void{
newUser = u;
});
return newUser;
}
UserFactory.GetCurrent looks like this:
public function GetCurrent(callback:Function):void{ }
But my understanding is there is no guarantee that when this function gets called, newUser will actually be the new user??
How do you accomplish this type of return function in Flex?
This way madness lies.
Seriously, you're better off not trying to force an asynchronous call into some kind of synchronous architecture. Learn how the event handling system works in your favour and add a handler for the result event. In fact, here's the advice straight from the flexcoders FAQ :
Q: How do I make synchronous data calls?
A: You CANNOT do synchronous calls. You MUST use the result event. No,
you can't use a loop, or setInterval or even callLater. This paradigm is
quite aggravating at first. Take a deep breath, surrender to the
inevitable, resistance is futile.
There is a generic way to handle the asynchronous nature of data service
calls called ACT (Asynchronous Call Token). Search for this in
Developing Flex Apps doc for a full description.
See my answer here:
DDD and Asynchronous Repositories
Flex and Flash Remoting is inherently asynchronous so fighting against that paradigm is going to give you a ton of trouble. Our service delegates return AsyncToken from every method and we've never had a problem with it.
If you want to ensure that the application doesn't render a new view or perform some other logic until the result/fault comes back, you could do the following:
Attach an event listener for a custom event that will invoke your "post result/fault code"
Make the async call
Handle the result/fault
Dispatch the custom event to trigger your listener from #1
Bear in mind this going to lead to a lot of annoying boilterplate code every time you make an async call. I would consider very carefully whether you really need a synchronous execution path.
You can't convert async call into sync one without something like "sleep()" function and as far as I know it is missing in AS3. And yes, it is not guaranteed that newUser would contain user name before return statement.
The AS3 port of the PureMVC framework has mechanisms for implementing synchronous operations in a Model-View-Controller context. It doesn't try to synchronize asynchronous calls, but it lets you add a synchronous application pattern for controlling them.
Here's an example implementation: PureMVC AS3 Sequential Demo.
In this example, five subcommands are run sequentially, together composing a whole command. In your example, you would implement getUser() as a command, which would call commandComplete() in the getURL() (or whatever) callback. This means the next command would be certain that the getUser() operation is finished.

Resources