由于作者已提到钠deprecated ,我正试图将我的代码移植到反应性香蕉。然而,两者之间似乎存在一些不协调,以至于我很难过度使用。
例如,在钠中很容易检索行为的当前值:
retrieve :: Behaviour a -> IO a
retrieve b = sync $ sample b
我不知道如何在反应香蕉
中这样做(我想要这个的原因是因为我试图将行为导出为dbus属性。可以从其他dbus客户端查询属性)
编辑:替换“民意调查”一词,因为它具有误导性
答案 0 :(得分:1)
如果你有一个行为建模你的属性的值,并且你有一个事件建模对属性值的传入请求,那么你可以使用(<@) :: Behavior b -> Event a -> Event b
1 使用当时属性具有的值,在传入请求时获取新事件。然后,您可以将其转换为回复请求所需的实际IO操作,并照常使用reactimate
。
答案 1 :(得分:0)
出于概念/体系结构的原因,Reactive Banana具有从Event
到Behavior
的功能,但反之亦然,鉴于FRP的性质和含义,它也是有意义的。我很确定你可以写一个轮询函数,但你应该考虑更改底层代码来代替公开事件。
您是否有理由无法将Behavior
更改为Event
?如果没有,那将是解决问题的好方法。 (从理论上讲,它甚至可以揭示到目前为止你一直忽视的设计缺点。)
答案 2 :(得分:0)
答案似乎是“它有点可能”。
但是,可以在execute:
的帮助下重新实施module Sync where
import Control.Monad.Trans
import Data.IORef
import Reactive.Banana
import Reactive.Banana.Frameworks
data Network = Network { eventNetwork :: EventNetwork
, run :: MomentIO () -> IO ()
}
newNet :: IO Network
newNet = do
-- Create a new Event to handle MomentIO actions to be executed
(ah, call) <- newAddHandler
network <- compile $ do
globalExecuteEV <- fromAddHandler ah
-- Set it up so it executes MomentIO actions passed to it
_ <- execute globalExecuteEV
return ()
actuate network
return $ Network { eventNetwork = network
, run = call -- IO Action to fire the event
}
-- To run a MomentIO action within the context of the network, pass it to the
-- event.
sync :: Network -> MomentIO a -> IO a
sync Network{run = call} f = do
-- To retrieve the result of the action we set up an IORef
ref <- newIORef (error "Network hasn't written result to ref")
-- (`call' passes the do-block to the event)
call $ do
res <- f
-- Put the result into the IORef
liftIO $ writeIORef ref res
-- and read it back once the event has finished firing
readIORef ref
-- Example
main :: IO ()
main = do
net <- newNet -- Create an empty network
(bhv1, set1) <- sync net $ newBehavior (0 :: Integer)
(bhv2, set2) <- sync net $ newBehavior (0 :: Integer)
set1 3
set2 7
let sumB = (liftA2 (+) bhv1 bhv2)
print =<< sync net (valueB sumB)
set1 5
print =<< sync net (valueB sumB)
return ()