How to create lifecycle aware components with Hilt?

Viewed 552

Let's say, I have a MediaRecorder class that I will be using in a different fragment which looks this way:

class Recorder @Inject constructor(
    lifecycle: Lifecycle,
    private val mediaRecorder: MediaRecorder
) : LifecycleObserver {

    init {
        lifecycle.addObserver(this)
    }

    fun startRecording() {
        mediaRecorder.prepare()
        mediaRecorder.start()
    }

    fun stopRecording() {
        mediaRecorder.stop()
        mediaRecorder.release()
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
    fun onPauseEvent() {
        mediaRecorder.pause()
    }
}

I want to inject here the lifecycle of the fragment/activity that I will be using here.

How can I do that?

1 Answers

Try out via activity context

tailrec fun Context.activity(): Activity? = this as? Activity
    ?: (this as? ContextWrapper)?.baseContext?.activity()

class MyClass @Inject constructor(@ActivityContext context: Context) : LifecycleObserver {

    init {
        val activity = context.activity() as AppCompatActivity
        activity.lifecycle.addObserver(this)
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_START)
    private fun onStart() {

    }

    @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
    private fun onStop() {

    }
}

If this class is shared between fragments then add @ActivityScoped annotation

Related