Last active
September 27, 2019 17:01
-
-
Save raloliver/094d9356a0a310a7e4c83137f8f33f14 to your computer and use it in GitHub Desktop.
RxJS: AsyncSubject, BehaviorSubject and ReplaySubject
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
//AsyncSubject: exibe apenas o último valor enviado antes da função “completed()” ser executada. | |
var subjectAsync = new Rx.AsyncSubject(); | |
var subscriptionAsync = subject.subscribe( | |
value => console.log(`My Value is ${value}`), | |
err => console.log(`Error message: ${err}`), | |
() => console.log('Completed!') | |
) | |
var counterAsync = 5, | |
intervalAsync = setInterval(()=>{ | |
subject.next(counterAsync--); | |
if(!counter){ | |
clearInterval(intervalAsync); | |
subject.complete() | |
} | |
}, 1000); | |
//BehaviorSubject: usamos um valor inicial que será utilizado na inscrição, se nenhum valor tiver sido enviado. | |
//BehaviorSubject: novos inscritos recebem os valores enviados. | |
//BehaviorSubject: use getValue() para retornar o último valor emitido (ou o valor inicial, caso não tenha enviado nenhum). | |
var subjectBeha = new Rx.BehaviorSubject(83); | |
var subscriptionBeha = subject.subscribe( | |
value => console.log(`My Value is ${value}`), | |
err => console.log(`Error message: ${err}`), | |
() => console.log('Completed!') | |
) | |
var counterBeha = 5, | |
intervalBeha = setInterval(()=>{ | |
subject.next(counterBeha--); | |
if(!counter){ | |
clearInterval(intervalBeha); | |
subject.complete() | |
} | |
}, 1000); | |
//ReplaySubject: armazena os últimos valores enviados. (tipo um buffer) | |
//ReplaySubject: novos inscritos recebem todos os valores enviados ou determinados na chamada da função. | |
//ReplaySubject: é possível definir a quantidade de valores armazenados. | |
var subjectReplay = new Rx.ReplaySubject(2); //armazenar os 2 últimos valores | segundo parâmetro: quanto tempo cada elemento ficará disponível (lifetime) | |
var subscriptionReplay = subject.subscribe( //esse inscrito vai receber todos, mas o replay vai armazenar apenas 2 | |
value => console.log(`My Value is ${value}`), | |
err => console.log(`Error message: ${err}`), | |
() => console.log('Completed!') | |
) | |
var counterReplay = 5, //enviamos 5 vezes durante o lyfe cycle | |
intervalReplay = setInterval(()=>{ | |
subject.next(counterReplay--); | |
if(!counter){ | |
clearInterval(intervalReplay); | |
subject.complete() | |
} | |
}, 1000); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment