ebeninki
ebeninki

Reputation: 989

Method with @OnLifecycleEvent annotation in multiple lifecycle methods

I have the following lifecycle methods in my fragment class:

override fun onPause() {
        super.onPause()
        releasePlayer()
}

override fun onStop() {
        super.onStop()
        if(Util.SDK_INT >= 24){
            releasePlayer()
        }
}

As you can see, they both call a method called releasePlayer(). Now, instead using these 2 lifecycle methods I wanted to put the releasePlayer() logic from the Fragment into an own separate class which implements the LifecycleObserver interface. So, whenever the onStart() or onResume() lifecycle methods are triggered, the releasePlayer() code in the separate class (observing the lifecycle methods) would be invoked. For that I have now this:

class PlayerLogic(private val lifecycleOwner: LifecycleOwner) : LifecycleObserver {

  init {
      lifecycleOwner.lifecycle.addObserver(this)
  }


  @OnLifecycleEvent(Lifecycle.Event.ON_START,Lifecycle.Event.ON_RESUME)
    private fun releasePlayer(){  // ..do some stuff }

}

But using @OnLifecycleEvent(Lifecycle.Event.ON_START,Lifecycle.Event.ON_RESUME) gives me an error telling me that the @OnLifecycleEvent annotation excepts only one argument.

So, how can I let releasePlayer() be invoked when the onStart() and onResume() are called. Is that possible ? If yes, how ?

Upvotes: 0

Views: 2600

Answers (1)

Francesc
Francesc

Reputation: 29320

Just duplicate it

@OnLifecycleEvent(Lifecycle.Event.ON_START)
fun start() {
    releasePlayer()
}

@OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
fun resume() {
    releasePlayer()
}

private fun releasePlayer() {
    // ..do some stuff
}

Upvotes: 2

Related Questions