```suspend fun requestStepsActivity(): List<Som...
# coroutines
m
Copy code
suspend fun requestStepsActivity(): List<Something> = suspendCancellableCoroutine { emitter ->
    val listener = object : SimpleEventListener() {
        override fun onSent() {
            emitter.resume(Something)
        }
        override fun onFailedSending() {
            emitter.resumeWithException(RuntimeException())
        }
    }

    try {
        someApi.addListener(listener)
        someApi.requestData()
    } catch (e: Throwable) {
        emitter.resumeWithException(e)
    } finally {
        someApi.removeListener(listener)
    }
}
m
I think you just have to call removeListener in both onSent and onFailedSending
m
and catch as well. and i must also include a cancelation callback and clean there also
that why my question:P
m
can
requestData
throw exception though?
m
Copy code
suspend fun requestStepsActivity(): List<Something> = suspendCancellableCoroutine { emitter ->
    val listener = object : SimpleEventListener() {
        override fun onSent() {
            cleanUp()
            emitter.resume(Something)
        }
        override fun onFailedSending() {
            cleanUp()
            emitter.resumeWithException(RuntimeException())
        }
    }

    emitter.invokeOnCancellation { cleanUp() }

    try {
        someApi.addListener(listener)
        someApi.requestData()
    } catch (e: Throwable) {
        cleanUp()
        emitter.resumeWithException(e)
    }
    
    fun cleanUp(){
        someApi.removeListener(listener)
    }
}
so the full code must be like this ?
its a bit tedius
m
it seems redundant for an API to throw exception through both listener and through regular throw
m
ya, i guess that is not necessary
but then i would need cancelation as well right ?
m
yes
also depending on the API you might not need callbacks in sent/failed.
If the API is one-shot then those callbacks would be dead anyway
m
what do you mean ?
m
well it depends on what
someApi
does
m
it returns data or an error
m
if
someApi
object is only used once, then you do not need to remove listener after success/error
since that listener will never be used anyway
m
well, i do not know what the api does. but its safer to remove to avoid a leak i guess
m
there shouldn't be any leaks since you only reference
emitter
from the listener
m
i mean, the SimpleEventListener can leak in the api if not removed, not the emitter
m
I guess all of that depends if you trust the API author
most APIs work by merging both into
requestData(listener)
though. Your example design looks a bit odd to me, unless listener can survive through multiple
requestData
calls, in case I think there are bigger issues.
m
ya, its kinda bad
there are two listener, one passed as argument that will forward success/error cases. but then there is an external global listener, than forwards the data
anyway, thanks for help 😛
m
np