coil-kt / coil

Image loading for Android and Compose Multiplatform.
https://coil-kt.github.io/coil/
Apache License 2.0
10.83k stars 664 forks source link

Guard against Dispatchers.Main.immediate being unavailable. #2699

Open colinrtwhite opened 3 days ago

colinrtwhite commented 3 days ago

Coil relies on immediate dispatching to resolve from its memory cache synchronously. Dispatchers.Main.immediate is available almost everywhere except test and preview environments (e.g. Paparazzi, Roborazzi, AndroidX screenshot testing lib, and Android Studio previews). Technically the main thread can be overridden in these cases with Dispatchers.setMain, but we want to avoid requiring that. In those cases, fall back to Dispatchers.Unconfined. This works fine for most cases as Coil makes no assumptions about the context it is in and its components are thread safe except:

As Dispatchers.Unconfined will only end up being used in test/non prod code I feel OK about making this change since in those cases you should also set ImageLoader.Builder.coroutineContext(EmptyCoroutineContext) to load images synchronously. It may make sense to set ImageLoader.Builder.coroutineContext(EmptyCoroutineContext) automatically if Dispatchers.Main.immediate can't be resolved, but I'm unsure.