Class: Porcupine::Observable

Inherits:
SimpleDelegator
  • Object
show all
Defined in:
lib/porcupine/observable.rb

Instance Method Summary collapse

Instance Method Details

#subscribe(*args, &block) ⇒ Object

Raises:

  • (ArgumentError)


5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# File 'lib/porcupine/observable.rb', line 5

def subscribe(*args, &block)
  raise ArgumentError unless block_given? || (args.first && args.first["onNext"])

  on_next = if block_given?
              block
            else
              args.first["onNext"]
            end

  on_error = args.first && args.first["onError"]

  wrapped = lambda do |value_or_exception|
    if value_or_exception.is_a?(Exception)
      on_error && on_error.call(value_or_exception)
    else
      on_next.call(value_or_exception)
    end
  end

  __getobj__.subscribe("onNext" => wrapped, "onError" => on_error)
end