我正在处理一些通过 websockets 与远程 API 交互的代码。我的数据层负责建立和监控 websocket 连接。它还包含应用程序可用于将要发送的 websocket 消息排入队列的方法。应用程序代码不应负责检查 websocket 连接的状态,即即发即弃。
理想情况下,我希望数据层的功能如下:
- 当数据层没有与 websocket 端点 (
self.isConnected == NO
) 的连接时,消息会在内部缓冲。 - 当连接可用时 (
self.isConnected == YES
),缓冲的消息会立即发送,并且任何后续消息都会立即发送。
这是我能想到的:
#import "RACSignal+Buffering.h"
@implementation RACSignal (Buffering)
- (RACSignal*)bufferWithSignal:(RACSignal*)shouldBuffer
{
return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
RACCompoundDisposable *disposable = [RACCompoundDisposable compoundDisposable];
NSMutableArray* bufferedValues = [[NSMutableArray alloc] init];
__block BOOL buffering = NO;
void (^bufferHandler)() = ^{
if (!buffering)
{
for (id val in bufferedValues)
{
[subscriber sendNext:val];
}
[bufferedValues removeAllObjects];
}
};
RACDisposable* bufferDisposable = [shouldBuffer subscribeNext:^(NSNumber* shouldBuffer) {
buffering = shouldBuffer.boolValue;
bufferHandler();
}];
if (bufferDisposable)
{
[disposable addDisposable:bufferDisposable];
}
RACDisposable* valueDisposable = [self subscribeNext:^(id x) {
[bufferedValues addObject:x];
bufferHandler();
} error:^(NSError *error) {
[subscriber sendError:error];
} completed:^{
[subscriber sendCompleted];
}];
if (valueDisposable)
{
[disposable addDisposable:valueDisposable];
}
return disposable;
}];
}
@end
最后,这是如何使用它的伪代码:
@interface APIManager ()
@property (nonatomic) RACSubject* requests;
@end
@implementation WebsocketDataLayer
- (id)init
{
self = [super init];
if (self) {
RACSignal* connectedSignal = RACObserve(self, connected);
self.requests = [[RACSubject alloc] init];
RACSignal* bufferedApiRequests = [self.requests bufferWithSignal:connectedSignal];
[self rac_liftSelector:@selector(sendRequest:) withSignalsFromArray:@[bufferedApiRequests]];
}
return self;
}
- (void)enqueueRequest:(NSString*)request
{
[self.requests sendNext:request];
}
- (void)sendRequest:(NSString*)request
{
DebugLog(@"Making websocket request: %@", request);
}
@end
我的问题是:这是缓冲值的正确方法吗?有没有更惯用的 RAC 方式来处理这个问题?