local Rx = require 'Rx'

local AnonymousObservable = Rx.AnonymousObservable
local validateNonNegativeInteger = Rx.internals.NumericArgument.validateNonNegativeInteger

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

return function(self, ...)

    local count = validateNonNegativeInteger('count', 1, 1, ...)

    return AnonymousObservable(function(observer)

        local remaining = count

        return self:subscribe(
            function(...)
                if remaining <= 0 then
                    observer:onNext(...)
                else
                    remaining = remaining - 1
                end
            end,
            function(...)
                return observer:onError(...)
            end,
            function(...)
                return observer:onCompleted(...)
            end)

    end, self)

end
