Gracefully intercept networking interruption errors

This commit is contained in:
2026-09-22 21:46:29 -07:00
committed by Tom
parent 509ac11749
commit 71a2146c4b
2 changed files with 15 additions and 4 deletions

View File

@@ -249,10 +249,14 @@ public class MainActivity extends AppCompatActivity {
int totalImported = 0;
String nextUrl = null;
do {
if (mImportDisposable != null && mImportDisposable.isDisposed()) break;
Open5eApiWrapper.Open5ePageResult page = Open5eApiWrapper.fetchPage(nextUrl);
if (mImportDisposable != null && mImportDisposable.isDisposed()) {
throw new InterruptedException("Open5e import was cancelled");
}
Open5eApiWrapper.Open5ePageResult page = Open5eApiWrapper.fetchPage(nextUrl, () -> mImportDisposable != null && mImportDisposable.isDisposed());
for (Monster monster : page.monsters) {
if (mImportDisposable != null && mImportDisposable.isDisposed()) break;
if (mImportDisposable != null && mImportDisposable.isDisposed()) {
throw new InterruptedException("Open5e import was cancelled");
}
try {
((MonsterCardsApplication) getApplication()).getMonsterRepository()
.saveMonster(monster)

View File

@@ -12,11 +12,13 @@ import com.majinnaibu.monstercards.models.Monster;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.InterruptedIOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.function.BooleanSupplier;
import com.majinnaibu.monstercards.utils.Logger;
@@ -29,7 +31,7 @@ public class Open5eApiWrapper {
}
@NonNull
public static Open5ePageResult fetchPage(@Nullable String urlStr) throws Exception {
public static Open5ePageResult fetchPage(@Nullable String urlStr, BooleanSupplier isCancelled) throws Exception {
if (urlStr == null || urlStr.isEmpty()) {
urlStr = BASE_URL;
}
@@ -52,8 +54,13 @@ public class Open5eApiWrapper {
BufferedReader reader = new BufferedReader(new InputStreamReader(in, StandardCharsets.UTF_8))) {
String line;
while ((line = reader.readLine()) != null) {
if (isCancelled.getAsBoolean()) {
throw new InterruptedException("Open5e network read was cancelled.");
}
sb.append(line);
}
} catch (InterruptedIOException e) {
throw new InterruptedException("Open5e network read was cancelled.");
}
String jsonPayload = sb.toString();