需要一些关于 RX 的帮助。我想定义 observable,它应该在创建第一个订阅时创建资源,为每个新订阅发布一次此资源实例,并且当所有订阅完成后,必须处置该资源实例。类似于 Observable.Using 的东西,但具有 Publish(value) 和 RefCount 行为。我所有使用标准运算符表达它的尝试都失败了。这段代码可以满足我的要求,但我认为必须有标准的方式来做到这一点。我真的不想重新发明轮子。
using System;
using System.Reactive.Linq;
using System.Reactive.Disposables;
namespace ConsoleApplication1
{
class Program
{
static void Main()
{
// this part is what i can't express in standart RX operators..
Res res = null;
RefCountDisposable disp = null;
var @using = Observable.Create<Res>(obs =>
{
res = res ?? new Res();
disp = disp == null || disp.IsDisposed ? new RefCountDisposable(res) : disp;
obs.OnNext(res);
return new CompositeDisposable(disp.GetDisposable(), disp, Disposable.Create(() => res = null));
});
// end
var sub1 = @using.Subscribe(Print);
var sub2 = @using.Subscribe(Print);
sub1.Dispose();
sub2.Dispose();
sub1 = @using.Subscribe(Print);
sub2 = @using.Subscribe(Print);
sub1.Dispose();
sub2.Dispose();
Console.ReadKey();
}
static void Print(object o)
{
Console.WriteLine(o.GetHashCode());
}
}
class Res : IDisposable
{
public Res()
{
Console.WriteLine("CREATED");
}
public void Dispose()
{
Console.WriteLine("DISPOSED");
}
}
}
输出:
CREATED
1111
1111
DISPOSED
CREATED
2222
2222
DISPOSED
我对标准运营商的“最佳”尝试:
var @using = Observable.Using(() => new Res(), res => Observable.Never(res).StartWith(res))
.Replay(1)
.RefCount();
输出是:
CREATED
1111
1111
DISPOSED
CREATED
1111 <-- this is "wrong" value
2222
2222
DISPOSED
谢谢!
附言。对不起我糟糕的英语=(