Observable
Observables are like an signal, except they do not execute code until the observable is subscribed to. This follows the standard Rx API surface for an observable.
Observables use a Subscription to emit values.
-- Constucts an observable which will emit a, b, c via a subscription
local observable = Observable.new(function(sub)
print("Connected")
sub:Fire("a")
sub:Fire("b")
sub:Fire("c")
sub:Complete() -- ends stream
end)
local sub1 = observable:Subscribe() --> Connected
local sub2 = observable:Subscribe() --> Connected
local sub3 = observable:Subscribe() --> Connected
sub1:Destroy()
sub2:Destroy()
sub3:Destroy()
Note that emitted values may be observed like this
observable:Subscribe(function(value)
print("Got ", value)
end)
--> Got a
--> Got b
--> Got c
Note that also, observables return a MaidTask which should be used to clean up the resulting subscription.
maid:GiveTask(observable:Subscribe(function(value)
-- do work here!
end))
Observables over signals are nice because observables may be chained and manipulated via the Pipe operation.
tip
You should always clean up the subscription using a Maid, otherwise you may memory leak.
Functions
isObservable
Observable.
isObservable
(
item:
any
) →
boolean
Returns whether or not a value is an observable.
new
Constructs a new Observable
local function observeAllChildren(parent)
return Observable.new(function(sub)
local maid = Maid.new()
for _, item in pairs(parent:GetChildren()) do
sub:Fire(item)
end
maid:GiveTask(parent.ChildAdded:Connect(function(child)
sub:Fire(child)
end))
return maid
end)
end
-- Prints out all current children, and whenever a new
-- child is added to workspace
local maid = Maid.new()
maid:GiveTask(observeAllChildren(workspace):Subscribe(print))
Pipe
Transforms the observable with the following transformers
Rx.of(1, 2, 3):Pipe({
Rx.map(function(result)
return result + 1
end);
Rx.map(function(value)
return string.format("%0.2f", value)
end);
}):Subscribe(print)
--> 2.00
--> 3.00
--> 4.00
Subscribe
Observable:
Subscribe
(
fireCallback:
function?
,
failCallback:
function?
,
completeCallback:
function?
) →
MaidTask
Subscribes immediately, fireCallback may return a maid (or a task a maid can handle) to clean up