RxJS in the Code Widget

Quick example of using the Code widget with RxJS code.

Demo: An Example of RxJS in Our Code Widget

You can use our Code widget to run RxJS code. Here’s how it looks:

Press + to interact
foo
main.js
<html>
<head>
<script src="/main.js"></script>
</head>
...
</html>

Explanation of Code

For demo purposes, we added simple RxJS code using the map() function, as you can see on lines 5, 8, 11, 14, and 17 above. The map() function can be used to do a range of things, but here we’ve used it to produce a simple calculation, using three values of x: 10, 100, and 1000. Because we used three values, the functions produced three outputs each:

  • Three sums
  • Three differences
  • Three products
  • Three quotients
  • Three exponentiated values

The very last output produces a result of infinity. This is because the result of y= 10001000y =\ {1000}^{1000} is too large of a number to print to the console.

A Note on Syntax

When you click the Run button in the Code widget above, the RxJS code will execute. A little bit of config is needed to make this work—see Setup: How to Dockerize RxJS for Your Course.

You probably noticed that there’s a file in the Code widget called foo with a script src attribute inside. There’s also the file main.js, which has the RxJS code the user runs.

The reason for this is that RxJS supports two methods for importing modules:

  • import { of } from 'rxjs';, and
  • const{of} = require('rxjs') ;

Only the second method works with Docker, which is necessary to add RxJS to our platform. Hence the syntax you see in the main.js file above, with the const{} and require() syntax:

const{of}  =require('rxjs') ;
const{ map } = require('rxjs/operators'); 

In the next lesson, you’ll see that RxJS can also work with our Single Page App (SPA) widget.