-
Notifications
You must be signed in to change notification settings - Fork 78
Expand file tree
/
Copy pathtake.lua
More file actions
40 lines (31 loc) · 880 Bytes
/
take.lua
File metadata and controls
40 lines (31 loc) · 880 Bytes
1
2
3
4
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
30
31
32
33
34
35
36
37
38
39
40
local Observable = require 'observable'
--- Returns a new Observable that only produces the first n results of the original.
-- @arg {number=1} n - The number of elements to produce before completing.
-- @returns {Observable}
function Observable:take(n)
n = n or 1
return Observable.create(function(observer)
local subscription
if n <= 0 then
observer:onCompleted()
return
end
local i = 1
local function onNext(...)
observer:onNext(...)
i = i + 1
if i > n then
if subscription then subscription:unsubscribe() end
observer:onCompleted()
end
end
local function onError(e)
return observer:onError(e)
end
local function onCompleted()
return observer:onCompleted()
end
subscription = self:subscribe(onNext, onError, onCompleted)
return subscription
end)
end