Imagine having two completely separate sections of code in two unrelated classes that are both listening to the same Observable from a service class.
class MyService {
private readonly subject = new Subject<any>();
public observe(): Observable<any> {
return this.subject.pipe();
}
}
class A {
constructor(private readonly service: MyService) {
service.observe().subscribe( async (value) => {
await this.awaitAnOperation(value);
console.log('Subscription complete for Class A', value);
});
}
}
class B {
constructor(private readonly service: MyService) {
service.observe().subscribe( (value) => console.log('Subscription complete for Class B', value));
}
}
The current issue is that when the service triggers an event, the log from class B
appears before A
, even though A
was subscribed first. The desired outcome is for all operations to run and complete before moving on to the next one. Although running synchronously would resolve the problem, A
requires an async operation and B
can only log after A
has finished logging.
A
and B
have no knowledge of each other and should remain independent. In languages like C#, we can make an async method execute synchronously using GetAwaiter().Wait();
without it being discouraged, especially when it must run on the main thread. It would be helpful to have a similar option in TypeScript/JavaScript.
EDIT
A
subscribes prior to B
. It's crucial that they also execute in the order they were subscribed. While this behavior is typically followed by default, executing a subscription on a different thread could cause the main thread to move on to the next subscription prematurely. This is a scenario that needs to be avoided somehow.