I didn’t understand this challenge completely and probably my solution is not correct but if the fragment will call onStop() just before the onDestroyView, we can remove the viewLifeCyclerObserver and add:
@OnLifecycleEvent(Lifecycle.Event.ON_STOP)
fun clearQueue(){
Log.i(TAG, "Clearing all request from queue")
requestHandler.removeMessages(MESSAGE_DOWNLOAD)
requestMap.clear()
}
@OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
fun tearDown(){
Log.i(TAG, "Destroying background thread")
fragmentLifeCycle?.removeObserver(this)
quit()
}
I also added a property to hold fragment’s lifecycle
var fragmentLifeCycle:Lifecycle?=null
set(value){
field = value
field?.addObserver(this.fragmentLifecycleObserver)
}
Actually, No. I also didn’t understand that much on what to do but you have an idea on what the book wants. My solution also goes like this… very similar to yours.
I also realized that in order to remove the Observer, we need to first add the observer but I’m not sure if we will really need to because it has already been done in PhotoGalleryFragment maybe??
private val observer = fragmentLifeCycleObserver
private val lifecycle: Lifecycle? = null
init {
lifecycle?.addObserver(observer)
}.
@OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
fun tearDown() {
Log.i(TAG, "Destroying background thread")
lifecycle?.removeObserver(observer)
quit() // will terminate the thread
}
And the book exactly says that you should automatically remove the observer when the lifecycleOwner's ON_DESTROY is called which is exactly what you did.
And also for the calling clearQueue() function hint.
override fun onDestroyView() {
super.onDestroyView()
lifecycle.removeObserver(
thumbnailDownloader.fragmentLifeCycleObserver)
thumbnailDownloader.clearQueue() // Course Challenge. Have the fragment clear the queue
} ```