Skip to content

Instantly share code, notes, and snippets.

@NyaGarcia
Last active April 24, 2020 15:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save NyaGarcia/2fb6f2232115babe23a475e6fbff72a2 to your computer and use it in GitHub Desktop.
Save NyaGarcia/2fb6f2232115babe23a475e6fbff72a2 to your computer and use it in GitHub Desktop.
Create Observables lazily with defer()
import { defer, of } from "rxjs";
const pokemon = ["Squirtle", "Charmander", "Bulbasaur", "Pikachu"];
function getRandomPokemon() {
return pokemon[Math.floor(Math.random() * 3)];
}
// Each subscriber to this Observable will receive a random Pokemon because the getRandomPokemon function is executed with each subscription
const randomPokemonForReal$ = defer(() => of(getRandomPokemon()));
// Each time we subscribe we'll receive different values, because we're subscribing to different Observables
randomPokemonForReal$.subscribe(console.log);
// Output: Charmander
randomPokemonForReal$.subscribe(console.log);
// Output: Squirtle
randomPokemonForReal$.subscribe(console.log);
// Output: Pikachu
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment