2014-01-22 36 views
2

我知道如何创建一个可观察并分配处置行动:如何为Observable设置处理动作?

Observable.Create(o => 
{ 
    // o.OnNext etc. 
    return Disposable.Create(() => { /* ... */ }); 
}); 

但现在我公司生产的查询语法可观察到的:

var observable = from x in otherObservable 
       select x; 

如何分配处置行动,这样的查询?

回答

0

您不会处理observable。您处置一个observable的订阅。

例子:

var observable = from x in otherObservable 
      select x; 

var sub = observable.Subscribe(DoStuff); 
sub.Dispose(); 
+0

我的问题是:如何调用当我调用_sub.Dispose(); _该处置方法内将被调用的操作。 –

+0

你是什么意思?你可以把你想要的任何动作放在你有'/ * ... * /' –

6

如果我理解正确的,你想“链”或“听”每当订阅配置。要做到这一点的方法之一是使用Finally运营商的IObservable<T>,因为这样的:

var ob = from x in Observable.Interval(TimeSpan.FromSeconds(1)) 
      select x; 

// Use Finally to create an intermediate IObservable 
var disposeSub = ob.Finally(() => Console.WriteLine("disposed")); 

// Subscribe to the intermediate observable instead the original one 
var yourSub = disposeSub.Subscribe(Console.WriteLine); 

// Wait for some numbers to print 
Thread.Sleep(TimeSpan.FromSeconds(4)); 

// "disposed" will be written on the console at this point 
yourSub.Dispose(); 

希望帮助!

+0

的地方你甚至可以直接从你的LINQ查询的第一行返回'.Finally((=){...} – cvbarros

2

我想你应该澄清你的问题。 “处理行为”的含义并不完全清楚。

调用使用Observable.Finally诉讼已提出,但这一行动将在第一下列条件满足运行:

  • 可观察到的发送OnCompleted()
  • 可观察到的发送OnError()
  • 订阅手柄被丢弃。

即你不能保证,当你呼吁订阅句柄Dispose的动作将被执行精确;它可能已经运行 - 但拨打Dispose可确保在呼叫Dispose返回之前调用它。

这可能是你所需要的 - 但是考虑你的话,你希望动作在过去的这些情况下运行 - 在手柄脱手,那么你就需要附加的动作到订阅句柄本身,即:

var otherDisposable = /* your observable */; 

Action disposingAction =() => Console.WriteLine("I am disposed!"); 

var subscription = otherDisposable.Subscribe(/* set your handlers here */); 

var disposable = new CompositeDisposable(
    subscription, 
    Disposable.Create(disposingAction)); 

/* The disposingAction is *only* run when this is called */ 
disposable.Dispose(); 

我想不出什么情况下会需要,虽然这个,我不知道是否Observable.Finally,卡洛斯的建议,是一个更适合!

+0

James认为这只是另一种方式,但要确保他的“Dispose”总是被调用,我认为你的建议更直接,使用'CompositeDisposable'。 – cvbarros