-
Notifications
You must be signed in to change notification settings - Fork 0
Observables and Promises
Asynchronous programming in World of Warcraft is a good thing when using it in the correct places.
An observable is an event stream that can live infinitly and notifies all subscribers when something happens. They should be unsubscribed if no newer event should be received.
There are two main classes.
Observable
Subscription
An observable will create a subscription when you subscribed to an observable (via .subscribe(...)
). This subscription can be unsubscribed (via .unsubscribe()
).
One example for reactive programming: I want to get notified when unit health changes.
import { observableFromEvent } from "@wartoshika/wow-qhun-core-ts/src/core";
// listen to UNIT_HEALTH event
const subscription = observableFromEvent("UNIT_HEALTH")
// subscribe to this event and every time one unit looses or gains health i shall be notified
.subscribe(unit => {
// print the unitId
print(`unit was ${unit[0]}`);
});
// later in the future
subscription.unsubscribe();
A more complex example: I want to get notified when player health changes.
import { observableFromEvent } from "@wartoshika/wow-qhun-core-ts/src/core";
// listen to UNIT_HEALTH event
const subscription = observableFromEvent("UNIT_HEALTH")
// before i should be notified, make sure that only player changes passes.
.filter(unit => unit[0] === "player")
// subscribe to this event and every time one unit looses or gains health i shall be notified
.subscribe(unit => {
print(`unit was ${unit[0]}`);
});
// later in the future
subscription.unsubscribe();
Promises are a one time asynchronous request/response thing. They can be resolved when the request succeded or rejected when an error occurs. The resolved Promise may have a payload attached.
One example for Promises: I shall get notified when i raise from the dead.
import { EventUtil } from "@wartoshika/wow-qhun-core-ts/src/core";
EventUtil.getPromise("PLAYER_ALIVE", 10000).done(() => {
print("I am alive!");
}, reason => {
print("I shall life under the dead...");
});
The promise will try 10 seconds to be resolved via PLAYER_ALIVE
event. If the timeout exceeds, the promise will be rejected.
Tip: Every
Observable
can be converted to aPromise
using.toPromise()
method on observables.
- Getting started
- What is Typescript and why i choose Typescript
- Available modules
- Core
- Database
- Locale
- Model
- Net
- Slash
- UI