问题描述
我想将一个 ReactiveCommand 连接到一个 ConnectableObservable,因为 observable 应该可以被多个订阅者连接.
I'd like to wire a ReactiveCommand up to a ConnectableObservable, since the observable should be connectable by multiple subscribers.
问题是 ReactiveCommand 只会调用 ConnectableObservable 上的 Subscribe 方法,而不是我想要的 Connect 方法.
The problem is that ReactiveCommand will only call the Subscribe method on the ConnectableObservable, rather than the Connect method as I would like.
下面的代码演示了我想要实现的目标.请注意由服务代码调用的 StartOrConnectService 方法.
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);
}
}
是否有某种方法可以将 ConnectableObservable 改编或包装为常规 Observable,以便在 ReactiveCommand 执行时调用 ConnectableObservable.Connect 方法?
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?
推荐答案
啊哈,原来我在寻找 RefCount
扩展方法 (introtorx),将 IConnectableObservable
转换回 IObservablecode>,但神奇地实现了 Connect 语义.#loveRX
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
这篇关于ReactiveCommand 和 ConnectableObservable的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!