Browse Source

Add Observable.find;

bjorn 10 years ago
parent
commit
36f21688a9
2 changed files with 38 additions and 2 deletions
  1. 11 1
      doc/README.md
  2. 27 1
      rx.lua

+ 11 - 1
doc/README.md

@@ -190,7 +190,7 @@ Returns a new Observable that only produces values of the first that satisfy a p
 
 Arguments:
 
-- `predicate` (`function`) - The predicate to filter values with.
+- `predicate` (`function`) - The predicate used to filter values.
 
 Returns:
 
@@ -198,6 +198,16 @@ Returns:
 
 ---
 
+#### `:find(predicate)`
+
+Returns a new Observable that produces the first value of the original that satisfies a predicate.
+
+Arguments:
+
+- `predicate` (`function`) - The predicate used to find a value.
+
+---
+
 #### `:first()`
 
 Returns a new Observable that only produces the first result of the original.

+ 27 - 1
rx.lua

@@ -266,7 +266,7 @@ function Observable:distinct()
 end
 
 --- Returns a new Observable that only produces values of the first that satisfy a predicate.
--- @arg {function} predicate - The predicate to filter values with.
+-- @arg {function} predicate - The predicate used to filter values.
 -- @returns {Observable}
 function Observable:filter(predicate)
   predicate = predicate or identity
@@ -290,6 +290,32 @@ function Observable:filter(predicate)
   end)
 end
 
+--- Returns a new Observable that produces the first value of the original that satisfies a
+-- predicate.
+-- @arg {function} predicate - The predicate used to find a value.
+function Observable:find(predicate)
+  predicate = predicate or identity
+
+  return Observable.create(function(observer)
+    local function onNext(x)
+      if predicate(x) then
+        observer:onNext(x)
+        return observer:onComplete()
+      end
+    end
+
+    local function onError(message)
+      return observer:onError(e)
+    end
+
+    local function onComplete()
+      return observer:onComplete()
+    end
+
+    return self:subscribe(onNext, onError, onComplete)
+  end)
+end
+
 --- Returns a new Observable that only produces the first result of the original.
 -- @returns {Observable}
 function Observable:first()