local Rx = require 'Rx'

local AbstractObserver = Rx.AbstractObserver
local ObservableBase = Rx.ObservableBase

--------------------------------------------------------------------------------

local ToArrayObserver = Rx.Class 'Rx.internals.ToArrayObserver' {

    AbstractObserver,
        -- superclass

    _observer = false,
        -- (Observer)

    _a = false,
        -- (table)

    ----------------------------------------------------------------------------

    __init = function(self, observer)
        self._observer = observer
        self._a = {}
    end,

    ----------------------------------------------------------------------------

    next = function(self, x)

        table.insert(self._a, x)

    end,

    ----------------------------------------------------------------------------

    error = function(self, err)

        self._observer:onError(err)

    end,

    ----------------------------------------------------------------------------

    completed = function(self)

        self._observer:onNext(self._a)
        self._observer:onCompleted()

    end,

}

--------------------------------------------------------------------------------

local ToArrayObservable = Rx.Class 'Rx.internals.ToArrayObservable' {

    ObservableBase,
        -- superclass

    _source = false,
        -- (Observable)

    __init = function(self, source)
        self._source = source
    end,

    subscribeCore = function(self, observer)
        return self._source:subscribe(ToArrayObserver(observer))
    end,

}

--------------------------------------------------------------------------------

return function(self)
    return ToArrayObservable(self)
end
