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
26
27
28
29
# File 'lib/porcupine/observable.rb', line 5

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

  on_next = if block_given?
              block
            else
              args.shift
            end

  on_error = !block_given? && args.shift

  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

  if on_error
    __getobj__.subscribe(wrapped, on_error, *args)
  else
    __getobj__.subscribe(wrapped)
  end
end