我想出了这个:
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 的某个地方是否确实存在类似的功能,因为我发现这个组合器太有用了,不能省略。