将Rx与键入的消息代理一起使用

时间:2010-10-04 09:47:34

标签: .net system.reactive

我有一个类似于Caliburn提供的类型化消息代理:

public interface IMessageBroker
{
    void Publish<T>(T message);
    IDisposable Subscribe<T>(Action<T> subscriber);
}

如何将订阅转换为IObservable?

我想要一个扩展方法,如下所示:

public static IObservable<T> Subscribe<T>(this IMessageBroker messageBroker)
{
    var subject = new Subject<T>();
    messageBroker.Subscribe<T>(subject.OnNext);
    return subject;
}

此实现中的问题是我无法取消订阅,因此泄漏。

欢迎使用更好的Subscribe方法名称。

2 个答案:

答案 0 :(得分:3)

试试这个(未经测试):

public static IObservable<T> ToObservable<T>(this IMessageBroker messageBroker)
{
    IObservable<T> observable = Observable.CreateWithDisposable<T>(o =>
        {
            return messageBroker.Subscribe<T>(o.OnNext);
        });
    return observable;
}

你应该能够像这样使用:

var observableBroker = messageBroker.ToObservable<int>();
var subject = new Subject<int>();
observableBroker.Subscribe(subject.OnNext);

//alternatively, there are overloads of Observerable.Subscribe which take lambdas:
observableBroker.Subscribe(t => DoSomethingWith(t));

答案 1 :(得分:0)

试试这个(经过测试

  

如何将订阅转换为IObservable?

您可以使用set logging on Enable logging. set logging off Disable logging. set logging file file Change the name of the current logfile. The default logfile is gdb.txt. set logging overwrite [on|off] By default, gdb will append to the logfile. Set overwrite if you want set logging on to overwrite the logfile instead. set logging redirect [on|off] By default, gdb output will go to both the terminal and the logfile. Set redirect if you want output to go only to the log file. show logging Show the current values of the logging settings. 创建以下扩展方法:

Observable.Create

注意:System.Reactive nuget包没有public static IObservable<T> AsObservable<T>(this IMessageBroker messageBroker) { return Observable.Create<T>(observer => messageBroker.Subscribe<T>(observer.OnNext)); }

或没有Rx(为什么?可能不想要依赖):

Observable.CreateWithDisposable