What is the best way to ensure that `kotlinx.coroutines.flow.retryWhen` only retries when the button is clicked?

In Android (Kotlin lang), I am retrieving data from an API using Flow. If the API throws an exception, such as no internet connection, a timeout, or an unexpected error, I want to catch it within kotlinx.coroutines.flow.retryWhen and retry the request. However, I only want to retry when a button is clicked by the user, not automatically. What is the best way to ensure that kotlinx.coroutines.flow.retryWhen only retries when the button is clicked?

I currently don’t have any code, but I want to understand the concept of linking retryWhen with a button click. I’m seeking best practices.

Someone may ask:

Why would you want to make it that complicated? Why not simply triggering another api call on the next button click?

I’ll answer this

Why should I create a new object of flow for every click? I’m seeking a solution using retryWhen. I successfully implemented this in RxJava, but it doesn’t work in Kotlin. I’m thinking of using deferred with await inside retryWhen, but if I don’t find a solution

Thank you.

I suppose you could call suspendCancellableCoroutine() inside the retryWhen block.

That being said, it sounds like you’re trying to be clever. I think you’re going to end up with complicated, hard-to-understand code. In the end you probably would have been better off creating a new flow on every click.