ReactiveCommand and ConnectableObservable

 ̄綄美尐妖づ 提交于 2020-01-23 18:55:27

问题


I'd like to wire a ReactiveCommand up to a ConnectableObservable, since the observable should be connectable by multiple subscribers.

The problem is that ReactiveCommand will only call the Subscribe method on the ConnectableObservable, rather than the Connect method as I would like.

The code below demonstrates what I'm trying to achieve. Notice the StartOrConnectService method that is called by service code.

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);
    }
}     

Is there some way of adapting or wrapping a ConnectableObservable to a regular Observable so the ConnectableObservable.Connect method is called when the ReactiveCommand executes?


回答1:


Aha, turns out I was looking for the RefCount extension method (introtorx), that converts an IConnectableObservable back into an IObservable, but magically implements the Connect semantics. #loveRX



来源:https://stackoverflow.com/questions/46911672/reactivecommand-and-connectableobservable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!