thenWithUpdate<R2> method
继续链式调用,传递提取的对象和响应,更新对象并返回(最后一步)
说明:这是链式调用的最后一步,更新对象后返回 M?,不能继续链式调用
与 thenWith 的区别:
thenWith:中间步骤,返回ChainResult,可以继续链式调用(支持可选参数更新对象)thenWithUpdate:最后一步,返回M?,不能继续链式调用
注意:nextRequest 回调中的 http.send(...) 是作为参数执行的,不是链式调用的继续
示例:
final result = await http.isLoading
.send(...)
.extractModel<FileUploadResult>(FileUploadResult.fromConfigJson)
.thenWith((uploadResult) => http.uploadToUrlResponse(...))
.thenWithUpdate<String>(
// nextRequest: 执行下一个请求(作为回调参数,不是链式调用)
(uploadResult, uploadResponse) => 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),
);
// result 是更新后的 FileUploadResult,不能继续链式调用
Implementation
Future<M?> thenWithUpdate<R2>(
Future<Response<dynamic>> Function(M extracted, Response<R> prevResponse)
nextRequest,
R2? Function(Response<dynamic> response) extractor,
M Function(M extracted, R2? extractedValue) updater,
) async {
if (!response.isSuccess) {
// 前一步失败,触发错误提示并关闭加载提示
response.handleError();
if (_hasChainLoading) {
HttpUtilSafeCall.closeChainLoading();
}
return null;
}
final nextResponse = await nextRequest(extracted, response);
if (!nextResponse.isSuccess) {
// 下一步失败,触发错误提示并关闭加载提示
nextResponse.handleError();
if (_hasChainLoading) {
HttpUtilSafeCall.closeChainLoading();
}
return null;
}
// 链路成功完成,关闭加载提示
if (_hasChainLoading) {
HttpUtilSafeCall.closeChainLoading();
}
final extractedValue = extractor(nextResponse);
return updater(extracted, extractedValue);
}