Observable wrapping

We have just learned in Observable Anatomy that the key operators next() , error() and complete is what makes our Observable tick, if we define it ourselves. We have also learned that these methods triggers a corresponding callback on our subscription.

Wrapping something in an observable means we take something that is NOT an Observable and turn it into one, so it can play nice with other Observables. It also means that it can now use Operators.

Wrapping an ajax call

  1. let stream = Rx.Observable.create((observer) => {
  2. let request = new XMLHttpRequest();
  3. request.open( GET’, url );
  4. request.onload =() =>{
  5. if(request.status === 200) {
  6. observer.next( request.response );
  7. observer.complete();
  8. } else {
  9. observer.error('error happened');
  10. }
  11. }
  12. request.onerror = () => {
  13. observer.error('error happened') }
  14. request.send();
  15. })
  16. stream.subscribe(
  17. (data) => console.log( data )
  18. )

Three things we need to do here emit data, handle errors and close the stream

Emit the data

  1. if(request.status === 200) {
  2. observer.next( request.response ) // emit data
  3. }

Handle potential errors

  1. else {
  2. observer.error('error happened');
  3. }

and

  1. request.onerror = () => {
  2. observer.error('error happened')
  3. }

Close the stream

  1. if(request.status === 200) {
  2. observer.next( request.response )
  3. observer.complete() // close stream, as we don't expect more data
  4. }

Wrapping a speech audio API

  1. console.clear();
  2. const { Observable } = Rx;
  3. const speechRecognition$ = new Observable(observer => {
  4. const speech = new webkitSpeechRecognition();
  5. speech.onresult = (event) => {
  6. observer.next(event);
  7. observer.complete();
  8. };
  9. speech.start();
  10. return () => {
  11. speech.stop();
  12. }
  13. });
  14. const say = (text) => new Observable(observer => {
  15. const utterance = new SpeechSynthesisUtterance(text);
  16. utterance.onend = (e) => {
  17. observer.next(e);
  18. observer.complete();
  19. };
  20. speechSynthesis.speak(utterance);
  21. });
  22. const button = document.querySelector("button");
  23. const heyClick$ = Observable.fromEvent(button, 'click');
  24. heyClick$
  25. .switchMap(e => speechRecognition$)
  26. .map(e => e.results[0][0].transcript)
  27. .map(text => {
  28. switch (text) {
  29. case 'I want':
  30. return 'candy';
  31. case 'hi':
  32. case 'ice ice':
  33. return 'baby';
  34. case 'hello':
  35. return 'Is it me you are looking for';
  36. case 'make me a sandwich':
  37. case 'get me a sandwich':
  38. return 'do it yo damn self';
  39. case 'why are you being so sexist':
  40. return 'you made me that way';
  41. default:
  42. return `I don't understand: "${text}"`;
  43. }
  44. })
  45. .concatMap(say)
  46. .subscribe(e => console.log(e));

Speech recognition stream

This activates the microphone in the browser and records us

  1. const speechRecognition$ = new Observable(observer => {
  2. const speech = new webkitSpeechRecognition();
  3. speech.onresult = (event) => {
  4. observer.next(event);
  5. observer.complete();
  6. };
  7. speech.start();
  8. return () => {
  9. speech.stop();
  10. }
  11. });

This essentially sets up the speech recognition API. We wait for one response and after that we complete the stream, much like the first example with AJAX.

Note also that a function is defined for cleanup

  1. return () => {
  2. speech.stop();
  3. }

so that we can call speechRecognition.unsubscribe() to clean up resources

Speech synthesis utterance, say

This is responsible for uttering what you want it to utter ( say ).

  1. const say = (text) => new Observable(observer => {
  2. const utterance = new SpeechSynthesisUtterance(text);
  3. utterance.onend = (e) => {
  4. observer.next(e);
  5. observer.complete();
  6. };
  7. speechSynthesis.speak(utterance);
  8. });

main stream hey$

  1. heyClick$
  2. .switchMap(e => speechRecognition$)
  3. .map(e => e.results[0][0].transcript)
  4. .map(text => {
  5. switch (text) {
  6. case 'I want':
  7. return 'candy';
  8. case 'hi':
  9. case 'ice ice':
  10. return 'baby';
  11. case 'hello':
  12. return 'Is it me you are looking for';
  13. case 'make me a sandwich':
  14. case 'get me a sandwich':
  15. return 'do it yo damn self';
  16. case 'why are you being so sexist':
  17. return 'you made me that way';
  18. default:
  19. return `I don't understand: "${text}"`;
  20. }
  21. })
  22. .concatMap(say)
  23. .subscribe(e => console.log(e));

Logic should be read as follows
heyClick$ is activated on a click on a button.
speechRecognition is listening for what we say and sends that result into heyClick$ where the switching logic determines an appropriate response that is uttered by say Observable.

all credit due to @ladyleet and @benlesh

Summary

One easier Ajax wrapping and one a little more advanced Speech API has been wrapped into an Observable. The mechanics are still the same though:
1) where data is emitted, add a call to next()
2) if there is NO more data to emit call complete
3) if there is a need for it, define a function that can be called upon unsubscribe()
4) Handle errors through calling .error() in the appropriate place. (only done in the first example)