ReactiveCommand和ConnectableObservable

时间:2017-10-24 13:20:00

标签: system.reactive reactiveui

我想将ReactiveCommand连接到ConnectableObservable,因为observable应该可以由多个订户连接。

问题是ReactiveCommand只会调用ConnectableObservable上的Subscribe方法,而不是我想要的Connect方法。

下面的代码演示了我想要实现的目标。请注意服务代码调用的StartOrConnectService方法。

public class Foo
{
    public IConnectableObservable<string> Connection { get; }

    public Foo(BarService barService)
    {
        Connection = Observable.Create<string>(observer =>
        {
            disp = barService.BarStream().Subscribe(
              bar => { 
                Console.WriteLine($"{bar}");
                observable.onNext("Connected");
              },
              ex => observable.onNext("Errored"),
              () => observable.onNext("Disconnected")
            );
            return disp;
        }).Publish();
    }

    // This method is called by service code.
    public IDisposable StartOrConnectService()
    {
        // bunch of other stuff going on here, but essentially calling connect
        return Connection.Connect();
    }

}

public sealed class FooViewModel : ReactiveObject
{
    public ReactiveCommand<Unit, string> ConnectCommand { get; }

    public FooViewModel(Foo foo)
    {
        ConnectCommand = ReactiveCommand
            .CreateFromObservable(() => foo.Connection);
    }
}     

是否有某种方法可以将ConnectableObservable调整或包装到常规Observable,以便在ReactiveCommand执行时调用ConnectableObservable.Connect方法?

1 个答案:

答案 0 :(得分:2)

啊哈,结果我正在寻找RefCount扩展方法(introtorx),它将IConnectableObservable转换回IObservable,但神奇地实现了连接语义。 #loveRX