https://kotlinlang.org logo
#compose-web
Title
# compose-web
y

Yan Pujante

03/16/2024, 6:31 PM
I think I may have found an issue with wasmJs and (event) listeners set from kotlin (see thread)
I have the following code to load an audio file and make sure it is loaded:
Copy code
suspend fun loadAudio(url: String): Audio {
    val audio = Audio(url)

  suspendCoroutine { continuation ->
    var listener: ((Event) -> Unit)? = null
    listener = { _: Event ->
      println("listener = $listener")
      if(listener != null) {
        // This remove call does not seem to work... hence the listener = null line
        audio.removeEventListener("canplaythrough", callback = listener)
        listener = null
        continuation.resume(Unit)
      }
    }
    println("listener = $listener")
    audio.addEventListener("canplaythrough", callback = listener)
  }

  return audio
}
The problem I am facing is that
removeListener
does not work and the listener keeps on being called. I hacked it around by setting
listener = null
otherwise
continuation.resume(Unit)
fails when called again. The same code in javascript works fine:
Copy code
const sound = new Audio('Ping.wav');
        const listener = (e) => {
            sound.removeEventListener("canplaythrough", listener);
            console.log('canplaythrough (listener)\n');
        }
        sound.addEventListener("canplaythrough", listener);
The listener is only called once and properly removed...
4 Views