dector
05/13/2019, 1:41 PMwithContext(IO)
is leaking scope through global queue after parent scope cancelation. Explicit withContext(coroutineContext + IO)
works as expected.
(Example in thread)class MyFragment : Fragment(), CoroutineScope by MainScope() {
// Resources allocated by this fragment
private val bitmaps = mutableListOf<Bitmap>()
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
launch(Default, CoroutineStart.UNDISPATCHED) {
loadAndDisplayData()
}
}
override fun onDestroy() {
coroutineContext.cancel()
super.onDestroy()
}
private suspend fun loadAndDisplayData() {
// Do heavy allocation (load data)
repeat(10) {
bitmaps += Bitmap.createBitmap(2056, 2056, Bitmap.Config.RGBA_F16)
}
// No memory leak
withContext(coroutineContext + Main) {
displayData()
}
// Leaking instance of MyFragment
//withContext(Main) {
// displayData()
//}
}
private fun displayData() {
/*...*/
}
}