Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 38 additions & 0 deletions content/features/featuresDeepDive/events/observables.md
Original file line number Diff line number Diff line change
Expand Up @@ -302,3 +302,41 @@ scene.onPointerUp = () => {
advancedTimer.stop();
}
```

## Usage with RxJS

[RxJS](https://rxjs.dev/) is a common library for handling Observables which are compliant with the [current ECMAScript Observable proposal](https://github.com/tc39/proposal-observable#ecmascript-observable). It provides a wide range of operators, allowing for advanced execution patterns.

The following (TypeScript) code can be used to convert a Babylon Observable into its RxJS equivalent:

```typescript
/**
* Wraps a Babylon Observable into an rxjs Observable
*
* @param bjsObservable The Babylon Observable you want to observe
* @example
* ```
* import { Engine, Scene, AbstractMesh } from '@babylonjs/core'
*
* const canvas = document.getElementById('canvas') as HTMLCanvasElement
* const engine = new Engine(canvas)
* const scene = new Scene(engine)
*
* const render$: Observable<Scene> = fromBabylonObservable(scene.onAfterRenderObservable)
* const onMeshAdded$: Observable<AbstractMesh> = fromBabylonObservable(scene.onNewMeshAddedObservable)
* ```
*/
export function fromBabylonObservable<T>(
bjsObservable: BJSObservable<T>
): Observable<T> {
return new Observable<T>((subscriber) => {
if (!(bjsObservable instanceof BJSObservable)) {
throw new TypeError("the object passed in must be a Babylon Observable");
}

const handler = bjsObservable.add((v) => subscriber.next(v));

return () => bjsObservable.remove(handler);
});
}
```