thenWith<R2, E> method
继续链式调用,传递提取的对象和响应(中间步骤)
参数说明:
nextRequest: 下一个请求(必需)extractor: 从响应中提取数据(可选),如果提供,会提取数据用于更新对象updater: 更新对象(可选),如果提供,会用提取的数据更新对象
返回类型:
- 如果提供了
updater,返回更新后的对象(ChainResult),可以继续链式调用 - 如果没有提供
updater,返回原始对象(ChainResult),可以继续链式调用
注意: 这是 ChainResult 上的方法,接收两个参数 (extracted, prevResponse)
如果是从 extractModel 等扩展方法调用,请使用 ExtractedValueExtension.thenWith(只接收一个参数)
示例1:中间步骤,不更新对象
final chainResult = await http.isLoading
.send(...)
.extractModel<FileUploadResult>(FileUploadResult.fromConfigJson)
.thenWith((uploadResult) => http.uploadToUrlResponse(...)) // ExtractedValueExtension.thenWith
.thenWith((uploadResult, prevResponse) => http.send(...)); // ChainResult.thenWith
示例2:中间步骤,更新对象并继续链式调用
final chainResult = await http.isLoading
.send(...)
.extractModel<FileUploadResult>(FileUploadResult.fromConfigJson)
.thenWith((uploadResult) => http.uploadToUrlResponse(...))
.thenWith(
(uploadResult, prevResponse) => http.send(
method: hm.post,
path: '/uploader/get-image-url',
data: {'image_key': uploadResult.imageKey},
),
extractor: (response) => response.extractField<String>('image_url'),
updater: (uploadResult, imageUrl) => uploadResult.copyWith(imageUrl: imageUrl),
)
.thenWith((updatedUploadResult, prevResponse) => http.send(...)); // 可以继续链式调用
注意: 如果需要最后一步更新对象并结束链式调用,请使用 thenWithUpdate 方法
Implementation
Future<ChainResult<M, R2>> thenWith<R2, E>(
Future<Response<R2>> Function(M extracted, Response<R> prevResponse)
nextRequest, {
E? Function(Response<R2> response)? extractor,
M Function(M extracted, E? extractedValue)? updater,
}) async {
if (!response.isSuccess) {
// 前一步失败,触发错误提示并关闭加载提示
response.handleError();
if (_hasChainLoading) {
HttpUtilSafeCall.closeChainLoading();
}
return ChainResult<M, R2>(
extracted: extracted,
response: response as Response<R2>,
hasChainLoading: false,
);
}
final nextResponse = await nextRequest(extracted, response);
// 如果下一步失败,触发错误提示并关闭加载提示
if (!nextResponse.isSuccess) {
nextResponse.handleError();
if (_hasChainLoading) {
HttpUtilSafeCall.closeChainLoading();
}
// 返回 ChainResult,但 hasChainLoading 设为 false(因为 loading 已关闭)
return ChainResult<M, R2>(
extracted: extracted,
response: nextResponse,
hasChainLoading: false,
);
}
// 如果提供了 extractor 和 updater,提取数据并更新对象
M finalExtracted = extracted;
if (extractor != null && updater != null) {
final extractedValue = extractor(nextResponse);
finalExtracted = updater(extracted, extractedValue);
}
// 传递链式调用的加载状态
return ChainResult<M, R2>(
extracted: finalExtracted,
response: nextResponse,
hasChainLoading: _hasChainLoading,
);
}