AsynHelper Java kitaplığı, eşzamansız çağrılar (ve bekleme) için bir dizi yardımcı sınıf / yöntem içerir.
Bir dizi yöntem çağrısı veya kod bloğunu eşzamansız olarak çalıştırmak istenirse , aşağıdaki kod parçacığında olduğu gibi AsyncTask .submitTasks yararlı bir yardımcı yöntem içerir .
AsyncTask.submitTasks(
() -> getMethodParam1(arg1, arg2),
() -> getMethodParam2(arg2, arg3)
() -> getMethodParam3(arg3, arg4),
() -> {
//Some other code to run asynchronously
}
);
Tüm eşzamansız kodların çalışması tamamlanana kadar beklemek istenirse, AsyncTask.submitTasksAndWait değişkeni kullanılabilir.
Ayrıca, zaman uyumsuz yöntem çağrısı veya kod bloğunun her birinden bir dönüş değeri elde etmek istenirse, AsyncSupplier .submitSuppliers , sonucun daha sonra yöntem tarafından döndürülen sonuç sağlayıcı dizisinden elde edilebilmesi için kullanılabilir. Örnek pasajı aşağıdadır:
Supplier<Object>[] resultSuppliers =
AsyncSupplier.submitSuppliers(
() -> getMethodParam1(arg1, arg2),
() -> getMethodParam2(arg3, arg4),
() -> getMethodParam3(arg5, arg6)
);
Object a = resultSuppliers[0].get();
Object b = resultSuppliers[1].get();
Object c = resultSuppliers[2].get();
myBigMethod(a,b,c);
Her yöntemin dönüş türü farklıysa, aşağıdaki parçacığı kullanın.
Supplier<String> aResultSupplier = AsyncSupplier.submitSupplier(() -> getMethodParam1(arg1, arg2));
Supplier<Integer> bResultSupplier = AsyncSupplier.submitSupplier(() -> getMethodParam2(arg3, arg4));
Supplier<Object> cResultSupplier = AsyncSupplier.submitSupplier(() -> getMethodParam3(arg5, arg6));
myBigMethod(aResultSupplier.get(), bResultSupplier.get(), cResultSupplier.get());
Eşzamansız yöntem çağrılarının / kod bloklarının sonucu, aynı iş parçacığındaki farklı bir kod noktasında veya aşağıdaki kod parçacığındaki gibi farklı bir iş parçacığında da elde edilebilir.
AsyncSupplier.submitSupplierForSingleAccess(() -> getMethodParam1(arg1, arg2), "a");
AsyncSupplier.submitSupplierForSingleAccess(() -> getMethodParam2(arg3, arg4), "b");
AsyncSupplier.submitSupplierForSingleAccess(() -> getMethodParam3(arg5, arg6), "c");
//Following can be in the same thread or a different thread
Optional<String> aResult = AsyncSupplier.waitAndGetFromSupplier(String.class, "a");
Optional<Integer> bResult = AsyncSupplier.waitAndGetFromSupplier(Integer.class, "b");
Optional<Object> cResult = AsyncSupplier.waitAndGetFromSupplier(Object.class, "c");
myBigMethod(aResult.get(),bResult.get(),cResult.get());