Facebook的Flux Dispatcher到Objective-C的移植
pod 'CLAFluxDispatcher'
将文件添加到您的源树中也可以,没有依赖项。
这是从Flux文档改编的
CLAFluxDispatcher
用于向已注册的回调广播有效负载。这种用法与通用的发布/订阅系统有两点不同:
例如,考虑这个假设的飞行目的地表单,当选择国家时,会选中一个默认城市
CLAFluxDispatcher *flightDispatcher = [CLAFluxDispatcher new];
// Keeps track of which country is selected
NSMutableDictionary *countryStore = @{@"country": [NSNull null]};
// Keeps track of which city is selected
NSMutableDictionary *cityStore = @{@"city": [NSNull null]};
// Keeps track of the base flight price of the selected city
NSMutableDictionary *flightPriceStore = @{@"price": [NSNull null]};
当用户更改选择的城市时,我们分发有效负载
[flightDispatcher dispatch:@{
@"actionType": @"city-update",
@"selectedCity": @"paris"
}];
此有效负载由cityStore
处理
[flightDispatcher registerCallback:^(NSDictionary *payload) {
if ([payload[@"actionType"] isEqualToString:@"city-update"]) {
cityStore[@"city"] = payload[@"selectedCity"];
}
}]
当用户选择国家时,我们分发有效负载
[flightDispatcher dispatch:@{
@"actionType": @"country-update",
@"selectedCountry": @"australia"
}];
此有效负载由两个存储处理
countryStore[@"dispatchToken"] = [flightDispatcher registerCallback:^(NSDictionary *payload) {
if ([payload[@"actionType"] isEqualToString:@"country-update"]) {
countryStore[@"country"] = payload[@"selectedCountry"];
}
}];
当注册更新countryStore
的回调时,我们保存返回的标记的引用。使用该标记与waitFor()
一起,我们可以确保在更新cityStore
的回调需要查询其数据之前,countryStore
已更新。
cityStore[@"dispatchToken"] = [flightDispatcher registerCallback:^(NSDictionary *payload) {
if ([payload[@"actionType"] isEqualToString:@"country-update"]) {
// `countryStore[@"country"]` may not be updated.
[flightDispatcher waitFor:@[countryStore[@"dispatchToken"]]];
// `countryStore[@"country"]` is now guaranteed to be updated.
// Select the default city for the new country
cityStore[@"city"] = getDefaultCityForCountry(countryStore[@"country"]);
}
}];
waitFor()
的用法可以链接,例如
flightPriceStore[@"dispatchToken"] =
[flightDispatcher registerCallback:^(NSDictionary *payload) {
if ([payload[@"actionType"] isEqualToString: @"country-update"]) {
[flightDispatcher waitFor: @[cityStore[@"dispatchToken"]]];
flightPriceStore[@"price"] =
getFlightPriceStore(countryStore[@"country"], cityStore[@"city"]);
}
else if ([payload[@"actionType"] isEqualToString: @"city-update"]) {
flightPriceStore[@"price"] =
getFlightPriceStore(countryStore[@"country"], cityStore[@"city"]);
}
}];
当您在清理对象时,请不要忘记使用保存的标记取消注册悬而未决的回调
[flightDispatcher unregisterCallback: self.flightPriceStore[@"dispatchToken"]];
确保country-update
有效负载按顺序调用存储已注册的回调:countryStore
、cityStore
,然后是flightPriceStore
。
@interface CLAFluxDispatcher : NSObject
- (void)dispatch:(NSDictionary *)payload;
- (void)waitFor:(NSArray *)dispatchTokens;
- (id)registerCallback:(CLAFluxDispatcherCallback)callback;
- (void)unregisterCallback:(id)dispatchToken;
- (BOOL)isDispatching;
@end
此软件遵从MIT许可证