I need to send an http request as soon as the user presses the back button and exits the fragment. I don't want to wait for a response from the server, I just need to shoot to the server. I can't do this in viewModelScope
because it is related to the fragment's life cycle and it will never happen. I tried to do this in a separate scope like CoroutineScope (Dispatchers.IO).launch {...}
but the effect is the same the coroutin doesn't execute.
My pseudo code below:
@HiltViewModel
class MyViewModel @Inject constructor(
private val sendAnalyticsUseCase: SendAnalyticsUseCase
) : ViewModel() {
...
fun sendAnalytics() {
CoroutineScope(Dispatchers.IO).launch {
sendAnalyticsUseCase()
}
}
...
}
@AndroidEntryPoint
class MyFragment : Fragment() {
private val viewModel: MyViewModel by viewModels()
...
override fun onResume() {
super.onResume()
requireActivity().onBackPressedDispatcher
.addCallback(viewLifecycleOwner, object : OnBackPressedCallback(true) {
override fun handleOnBackPressed() {
viewModel.sendAnalytics()
findNavController().popBackStack()
}
})
}
}