0

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()
                }
            })
    }
}

kazhiu
  • 749
  • 9
  • 21

1 Answers1

0

For things like that, there is GlobalScope

    GlobalScope.launch(Dispatchers.IO) {
        sendAnalyticsUseCase()
    }
TheLibrarian
  • 1,540
  • 1
  • 11
  • 22
  • Thank you for your response. I know GlobalScope but it's not recommended, it causes memory leaks. My application is Single Activity Architecture so I can inject viewModel from MainActivity into a Fragment and make an API request on it. But I think I should use WorkManager for this. I don't know which is better :) – kazhiu Oct 13 '22 at 11:08
  • Ok, but I think you still can define CoroutineScope as you tried but not in the view model but in some component/object that lives longer than the view model - e.g. some singleton? – TheLibrarian Oct 13 '22 at 11:12
  • I found something interesting https://developer.android.com/kotlin/coroutines/coroutines-best-practices#create-coroutines-data-layer. I think I have a solution. Take a look at the ArticlesRepository class. This is exactly the case for me :) – kazhiu Oct 13 '22 at 11:40
  • Yeah, that's what said :-). Sorry if I didn't explain it properly. – TheLibrarian Oct 13 '22 at 11:46
  • Don't worry. The goal has been achieved. Thanks again :) – kazhiu Oct 13 '22 at 11:58