1.【決策邊界|網路與資料】 App 要把三種檔案送出去:
有三種做法:
請寫下:
我的回答:(待補)
2.【預測再驗證|持久化與離線】 照片上傳的三層都各自寫了重試:
// 第一層:OkHttp 攔截器,遇到 IOException 或 5xx 就再送一次,最多再送 3 次
class RetryInterceptor(private val maxRetries: Int = 3) : Interceptor {
override fun intercept(chain: Interceptor.Chain): Response {
var attempt = 0
while (true) {
try {
val response = chain.proceed(chain.request())
if (response.code < 500 || attempt == maxRetries) return response
response.close()
} catch (e: IOException) {
if (attempt == maxRetries) throw e
}
attempt++
}
}
}
// 第二層:OkHttpClient 本身,retryOnConnectionFailure 維持預設值
val uploadClient = OkHttpClient.Builder()
.addInterceptor(RetryInterceptor())
.build()
// 第三層:WorkManager
@HiltWorker
class PhotoUploadWorker @AssistedInject constructor(
@Assisted context: Context,
@Assisted params: WorkerParameters,
private val uploader: PhotoUploader, // 用 uploadClient 把照片 PUT 到預簽網址;網址在排入佇列時取得,存在 Room
) : CoroutineWorker(context, params) {
override suspend fun doWork(): Result {
if (runAttemptCount >= 5) return Result.failure()
val photoId = inputData.getString("photoId") ?: return Result.failure()
return when (uploader.put(photoId)) {
PutOutcome.Ok -> Result.success()
PutOutcome.Retryable -> Result.retry() // IOException 或 5xx
PutOutcome.Rejected -> Result.failure() // 其他 4xx
}
}
}
// 排入佇列時:網路連上才執行、EXPONENTIAL 退避、起始 30 秒
下面每個情境,先寫下你的預測,再用 MockWebServer 加 WorkManager 的測試工具(work-testing)或實機驗證:
failure,大約經過多久?retryOnConnectionFailure 有沒有參與?getWorkInfoByIdFlow 讀 Worker 以 setProgress 回報的進度,在兩次執行之間,進度條會顯示什麼?最後回答:
我的回答:(待補)