Last active
April 24, 2020 15:22
-
-
Save NyaGarcia/2fb6f2232115babe23a475e6fbff72a2 to your computer and use it in GitHub Desktop.
Create Observables lazily with defer()
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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