'How to stop/destroy a fragment when proceeding with the next fragment

I have a Fragment A that execute a loop request with a Server HTTP. When the app navigate to the next Fragment B the activity in Fragment A (requests to server) doesn't stop. How can i destroy that? For example this is the my OnlyFragment and inside a SpaceView there is a loop request, when i call togameover() i go to the next fragment but the loop inside the SpaceView it is not destroyed.

class OnlineFragment : Fragment() {
private var binding: StartfragmentBinding? = null
private var spaceView: SpaceView? = null
private lateinit var backgroundMusic: MediaPlayer
private lateinit var window: Window
object size{
    var x = 0
    var y = 0
}
override fun onCreateView(
    inflater: LayoutInflater, container: ViewGroup?,
    savedInstanceState: Bundle?
): View? {
    (activity as AppCompatActivity?)!!.supportActionBar!!.hide()
    getActivity()?.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);

    val soundEffects = SoundEffects(requireContext())

    soundEffects.playSound(SoundEffects.backgroundMusic)

    val outMetrics = DisplayMetrics()

    getActivity()?.getWindow()?.addFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
    window = activity?.getWindow()!!
    window.attributes.width
    window.attributes.height

    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.R) {
        val display = activity?.display
        display?.getRealMetrics(outMetrics)
    } else {
        @Suppress("DEPRECATION")
        val display = activity?.windowManager?.defaultDisplay
        @Suppress("DEPRECATION")
        display?.getMetrics(outMetrics)
    }

    size.y = outMetrics.heightPixels
    size.x = outMetrics.widthPixels




    backgroundMusic = MediaPlayer.create(requireContext(), R.raw.background_music)
    backgroundMusic.isLooping = true
    backgroundMusic.start()

    spaceView = SpaceView(requireContext(), size, this)
    return spaceView
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)

}
fun togameover(){

    Handler(Looper.getMainLooper()).post {
        findNavController().navigate(R.id.action_onlineFragment_to_gameoveronlinefragment)
    }
}
override fun onResume() {
    super.onResume()

    spaceView?.resume()
}
override fun onStart() {
    super.onStart()
    Conf.canPoll=true

}

override fun onDestroyView() {
    super.onDestroyView()

}
override fun onPause() {
    super.onPause()
    Conf.canPoll=false
    backgroundMusic.release()
    spaceView?.pause()

}

}



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source