-module(r_server).
-export([r_spawn/2, r_spawn/3, r_loop/3, start/0]).


r_loop(Funk,State,Delay) ->
	receive Arg -> 
		Ret = Funk(Arg,State), 
		r_loop(Funk,Ret,Delay)
	after Delay ->
		Ret = Funk(expire,State),
		r_loop(Funk,Ret,Delay)
	end.

r_spawn(Funk,With) -> r_spawn(Funk,With,infinity).
r_spawn(Funk,With,Delay) when is_function(Funk,2) ->
	Pid = spawn(?MODULE,r_loop,[Funk,With,Delay]),
	Emit = fun (Arg) -> Pid ! Arg end,
	{ok,Emit}.

start()->
	Fn = fun (Arg,_) -> io:format("~p~n",[Arg]) end,
	{ok,Print} = r_spawn(Fn,[]),
	Print("tbrnk"),
	init:stop().
	
