0

我有如下所示的 F# 代码:

module O = Control.Observable
//...
use ss = serve' 4000
         |> O.subscribe
            (fun c -> use cs = RSS.items
                               |> O.subscribe (bytes >> c.SendAll) |> ignore)

在哪里

serve'    : int -> IObservable<Socket>
c         : Socket
RSS.items : IObservable<XElement>
bytes     : XElement -> byte []
c.SendAll : byte [] -> unit
  • cs保留直到c.SendAll失败的最惯用的方法是什么?
  • 是否有或者是否可以定义Observable.subscribeUntilError(action)如果action失败,订阅会在哪里被处理;否则action只要IObservable一直推就跑?
4

1 回答 1

0

我想出了这个:

let inline Δ<'a> = Unchecked.defaultof<'a>
let inline LOG x = printf "%A" x

module O = Observable
  let d = ref (Δ:IDisposable)
  let b x = try a x with e -> LOG e; let s = !d in if s <> Δ then s.Dispose()
  d := o |> O.subscribe b
  {
    new IDisposable with
      member x.Dispose() = let s = !d in if s <> Δ then d := Δ; s.Dispose()
  }

为了证明差异,请尝试main

使用subscribe

use s = new Subject<int>()
use x = s |> O.subscribe (fun _ -> raise <| Exception ())
use y = s |> O.subscribe (printf "%i")
s.OnNext 20

应用程序崩溃:

Unhandled Exception: System.Exception: Exception of type 'System.Exception' was thrown.
   at Microsoft.FSharp.Core.Operators.Raise[T](Exception exn)
   at Program.System.x@604-5.Invoke(Int32 _arg1) in C:\Eniox\Eniox.News.Google\Eniox.News.Google\Program.fs:line 60
   at Microsoft.FSharp.Control.CommonExtensions.SubscribeToObservable@1915.System-IObserver`1-OnNext(T value)
   at System.Reactive.Observer`1.OnNext(T value)
   at System.Reactive.Subjects.Subject`1.OnNext(T value)
   at Program.System.main(String[] args) in C:\Eniox\Eniox.News.Google\Eniox.News.Google\Program.fs:line 606

现在使用subscribeUE

use s = new Subject<int>()
use x = s |> O.subscribeUE (fun _ -> raise <| Exception ())
use y = s |> O.subscribe   (printf "%i")
s.OnNext 20

愉快地处理订阅x,应用程序继续运行没有打嗝并正常退出!输出:_ LOG = ignore

20

我很想知道在 RX 2.0 的某个地方是否确实存在类似的功能,因为我发现这个组合器太有用了,不能省略。

于 2012-08-02T03:31:22.020 回答