create

signature: create(subscribe: function)

Create an observable with given subscription function.

create - 图1

Examples

Example 1: Observable that emits multiple values

( jsBin |
jsFiddle )

  1. import { Observable } from 'rxjs/Observable';
  2. /*
  3. Create an observable that emits 'Hello' and 'World' on
  4. subscription.
  5. */
  6. const hello = Observable.create(function(observer) {
  7. observer.next('Hello');
  8. observer.next('World');
  9. });
  10. //output: 'Hello'...'World'
  11. const subscribe = hello.subscribe(val => console.log(val));
Example 2: Observable that emits even numbers on timer

( jsBin |
jsFiddle )

  1. import { Observable } from 'rxjs/Observable';
  2. /*
  3. Increment value every 1s, emit even numbers.
  4. */
  5. const evenNumbers = Observable.create(function(observer) {
  6. let value = 0;
  7. const interval = setInterval(() => {
  8. if (value % 2 === 0) {
  9. observer.next(value);
  10. }
  11. value++;
  12. }, 1000);
  13. return () => clearInterval(interval);
  14. });
  15. //output: 0...2...4...6...8
  16. const subscribe = evenNumbers.subscribe(val => console.log(val));
  17. //unsubscribe after 10 seconds
  18. setTimeout(() => {
  19. subscribe.unsubscribe();
  20. }, 10000);

Additional Resources


:file_folder: Source Code:
https://github.com/ReactiveX/rxjs/blob/master/src/internal/observable/GenerateObservable.ts