Hi everyone :slightly_smiling_face: I'm looking to...
# getting-started
j
Hi everyone 🙂 I'm looking to convert a callback from a 3rd party sdk we're using to a StateFlow and I can't for the life of me find something that works 😕 Code looks like that:
Copy code
class Provider {

    private val listener by lazy {
        object: 3rdPartyListener {
            // Bunch of callbacks

            // The one I actually care about
            override fun onError() {
                // Spam errors when in errors, do nothing otherwise
            }
        }
    }
}
I've read about
callbackFlow
but I can't quite make it work. For the use case of a callback that spam error / do nothing, AI is suggesting using a
debounce
but I don't know, that seems weird... Any help / suggestions appreciated! 🙏
t
callbackFlow
should be what you need. What did you try with it?
d
You need to wrap the callbacks in the callbackFlow builder and call the methods that will then emit the values to the flow. Checkout this example https://kotlinlang.org/api/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.flow/callback-flow.html
Copy code
class Provider {

    private val listenerFlow = callbackFlow {

        object: 3rdPartyListener {
            // Bunch of callbacks

            // The one I actually care about
            override fun onError(e: Error) {
                // Spam errors when in errors, do nothing otherwise
                // Emit the error to the flow
                trySend(e)
            }
        }
    }
}
j
sorry for being so late at getting back to you, day off + the feature this question is part off is just a tough cookie 😅 I think what we're not seing is how the callbackflow can help us with the "onError callback stopped, means we need to produce a new state in our stateflow"
l
How do you check that "onError callback stopped"? With a timeout?
You can then collect the flow using
withTimeoutOrNull()
and if there were no "onError" events then emit some other UiState. Modularize the solution, don't try to put everything into the
callbackFlow
. Did I get your question right?