Skip to content

Commit

Permalink
Add rxjs example
Browse files Browse the repository at this point in the history
[This forum post](https://forum.babylonjs.com/t/rxjs-observable/10438/5) discussed the issue of wrapping BJS Observables into rxjs. There even was an [issue opened](BabylonJS#140), but no PR.
  • Loading branch information
stefanpl authored Feb 4, 2023
1 parent 223ae62 commit 3711d5a
Showing 1 changed file with 38 additions and 0 deletions.
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);
});
}
```

0 comments on commit 3711d5a

Please sign in to comment.