Skip to content

Commit

Permalink
subject test
Browse files Browse the repository at this point in the history
  • Loading branch information
m1dnight committed May 17, 2018
1 parent 1ba5d03 commit 1c55eb1
Show file tree
Hide file tree
Showing 3 changed files with 58 additions and 1 deletion.
23 changes: 23 additions & 0 deletions lib/subject.ex
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
defmodule Subject do
alias Observables.GenObservable

@moduledoc """
Subject defines functions to create and interact with subjects.
A Subject is an observable which acts as a regular observer. It can be observed as usual, but it also allows the programmer to manually send messages to the process. The Subject will then emit the values.
Have a look at test/subject_test.ex for a simple example.
"""

def create() do
{:ok, pid} = GenObservable.spawn_supervised(Observables.Subject)

{fn observer ->
GenObservable.send_to(pid, observer)
end, pid}
end

def next({_f, pid}, v) do
GenObservable.send_event(pid, v)
end
end
2 changes: 1 addition & 1 deletion mix.exs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ defmodule Observables.MixProject do
def project do
[
app: :observables,
version: "0.1.7",
version: "0.1.9",
elixir: "~> 1.6",
start_permanent: Mix.env() == :prod,
deps: deps(),
Expand Down
34 changes: 34 additions & 0 deletions test/subject_test.exs
Original file line number Diff line number Diff line change
@@ -1,2 +1,36 @@
defmodule SubjectTest do
use ExUnit.Case
alias Observables.{Obs, GenObservable}
require Logger

@tag :subject
test "subject" do
Code.load_file("test/util.ex")

# Create a subject.
testproc = self()
s = Subject.create()

# Print out all the values that this subject produces,
# and forward them to the testproc.
s
|> Obs.each(fn v -> IO.puts("Subject produced #{v}") end)
|> Obs.each(fn v -> send(testproc, {:test, v}) end)

# Send some values to the subject, and make sure we receive them.
Subject.next(s, 10)
Subject.next(s, 20)
Subject.next(s, 30)
Test.Util.sleep(2000)

assert_receive({:test, 10}, 1000, "did not get this message!")
assert_receive({:test, 20}, 1000, "did not get this message!")
assert_receive({:test, 30}, 1000, "did not get this message!")

receive do
x -> flunk("Mailbox was supposed to be empty, got: #{inspect(x)}")
after
0 -> :ok
end
end
end

0 comments on commit 1c55eb1

Please sign in to comment.