這應當其中Rx迎刃而解。問題是如何知道互聯網是否可用?它是基於其他消費者訂閱,是基於另一種方法(如Connect()
方法)還是某些正在推送給您的事件(如WCF頻道狀態更改事件)?
根據這個答案,你似乎只需要封裝你的Take(1)和Replay(1)。
public class IServiceClient
{
IObservable<DateTime> LastConnnected { get; }
}
public class ServiceClient : IServiceClient, IDisposable
{
private readonly IDisposable _connection;
private readonly IObservable<DateTime> _lastConnnected;
public ServiceClient()
{
//Question 1) where does the 'Connected' sequence come from i.e. what is it that tells you that you have internet connectivity?
//Question 2) When should the subscription be made to 'Connected'? Here I cheat and do it in the ctor, not great.
var connected = Connected.Replay(1)
.Where(isConnected=>isConnected)
.Take(1)
.Select(_=>DateTime.UtcNow);
_lastConnnected = connected;
_connection = connected.Connect();
}
public IObservable<DateTime> LastConnnected{ get {return _lastConnnected; } }
public void Dispose()
{
_connection.Dispose();
}
}
這確實會給你一些其他問題以回答例如什麼是告訴你,如果你有互聯網連接和什麼資源管理計劃呢?
更新代碼
public interface IServiceClient
{
IObservable<DateTime> LastConnnected { get; }
}
public class ServiceClient : IServiceClient, IDisposable
{
private readonly IDisposable _connection;
private readonly IObservable<bool> _lastConnnected;
public ServiceClient(IObservable<ConnectionState> connectedStates)
{
var cachedStates = connectedStates.Select(state=>state.IsConnected).Replay(1);
_lastConnnected = cachedStates;
_connection = cachedStates.Connect();
}
public IObservable<DateTime> LastConnnected
{
get
{
return _lastConnnected.StartWith(IsConnected())
.Where(isConnected=>isConnected)
.Take(1)
.Select(_=>DateTime.UtcNow);
}
}
//....
public void Dispose()
{
_connection.Dispose();
}
}
你可以用.Aggregate做到這一點 - 但在這種情況下,我會建議書面方式自己的類/包裝,你可能想要控制的訂閱prozess好一點 – Carsten
你可以絕對使用Rx做到這一點,但是當只有一個通知時,異步方法更容易。 –