某些SDK中的函数向我返回了CompletableFuture。达到该值后如何正确读取。
我的代码:
autoreleasepool {
//set FPS
var sampleTimingInfo: CMSampleTimingInfo = CMSampleTimingInfo(duration: kCMTimeInvalid, presentationTimeStamp: CMTime(), decodeTimeStamp: kCMTimeInvalid)
var newBuffer: CMSampleBuffer! = nil
CMSampleBufferGetSampleTimingInfo(sampleBufferMain, 0, &sampleTimingInfo);
sampleTimingInfo.duration = CMTimeMake(1, 15) // Specify new frame rate.
sampleTimingInfo.presentationTimeStamp = CMTimeAdd(self.previousPresentationTimeStamp, sampleTimingInfo.duration)
self.previousPresentationTimeStamp = sampleTimingInfo.presentationTimeStamp
let status: OSStatus = CMSampleBufferCreateCopyWithNewTiming(kCFAllocatorDefault, sampleBufferMain, 1, &sampleTimingInfo, &newBuffer);
if status == noErr {
let appendResult = self.videoWriterInput?.append(newBuffer)
if appendResult == false {
printError("writer status: \(String(describing: self.videoWriter?.status.rawValue))")
printError("writer error: \(self.videoWriter?.error.debugDescription ?? "")")
}
} else {
print("write error")
}
}
sendAsync()代码(在SDK中):
CompletableFuture<Web3ClientVersion> web3clientCompletableFuture;
web3clientCompletableFuture = web3jNode.web3ClientVersion().sendAsync();
我可以使用get()访问返回的数据,但这将使整个过程同步并阻止UI。
我已经检查了Android API Reference上的函数签名,例如:
public CompletableFuture<T> sendAsync() {
return web3jService.sendAsync(this, responseType);
}
但是似乎我需要一些代码示例。
[注意:我对lambda不太熟悉]
答案 0 :(得分:0)
这是CompletableFuture的tutorial that has examples that show you how to use these powerful methods。如果您在处理未来后必须返回值,那么您就可以使用thenApply()是正确的。但是,如果您只是想处理未来而不返回任何内容,则应使用thenAccept()和thenRun()。示例中还列出了其他方法。
这里是一个仅返回整数类型的CompletableFuture的示例:
CompletableFuture<Integer> mynumber = null;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
mynumber = CompletableFuture.supplyAsync(() -> {
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
throw new IllegalStateException(e);
}
return 4 * 4;
});
}
这里arg是上述步骤的结果(CompletableFuture),在您的情况下是从SDK接收的数据。您将附加一个回调方法(thenApply())并执行您想使用的任何方法。根据您的实现,可以附加多个thenApply()。在这里,我正在调用一个将获取结果并对其进行一些计算的方法。
CompletableFuture<Integer> willdoStuff = null;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
willdoStuff = mynumber.thenApply(arg -> {
compute(arg);
return arg / 2;
});
}
public void compute(int someInt){
Toast.makeText(getApplicationContext(), "The result of the computation is" + someInt, Toast.LENGTH_LONG).show();
}
只需注释掉睡眠代码即可在主线程中执行此代码。 Lambda函数只是输入和输出,{}之前的参数是输入,而{}内的语句实际上是一个对arguments(input)起作用的函数。您可能要问与此有关的其他问题。