Home > database >  Can I create an instance manually when I have to use Hilt as dependency injection?
Can I create an instance manually when I have to use Hilt as dependency injection?

Time:04-22

I use Hilt as dependency injection in my project.

The ObjectModule module provides the instance of MediaRecorder, so I can use it in both SoundViewModel and HandleMeter.

In order to release resources, I have to assign null to mRecorder in fun stop() of SoundViewModel, so I need to create an instance of MediaRecorder in fun play() as needed.

1: Do I need create the instance using mRecorder = MediaRecorder() by myself? Can I get it from dependency injection ?

2: Will the instance of MediaRecorder in class HandleMeter @Inject constructor(val mRecorderFromDI: MediaRecorder) be recreated by dependency injection again when I have created it using mRecorder = MediaRecorder() in fun play() ?

@HiltViewModel
class SoundViewModel @Inject constructor(
    private val aHandleMeter: HandleMeter,
    private var mRecorder: MediaRecorder?
 ): ViewModel() {

    fun play() {
        //In order to handel re-play, so I write the following code.
        if (mRecorder==null) {
            mRecorder =  MediaRecorder()  //Do I need create by myself? Can I get it from dependency injection ?
        }
        
        mRecorder?.let {
            with(it) {
                setAudioSource(MediaRecorder.AudioSource.MIC);
                 ...
                prepare()
                start()
            }
        }

        val my= aHandleMeter.getMSoundDensity() 
        ...
    }
    
    fun stop() {
        try {          
            mRecorder?.stop()    
            mRecorder?.release()
            mRecorder = null
        } catch (e: Exception) {
        }
    }  
 
}


@InstallIn(SingletonComponent::class)
@Module
object ObjectModule {
    @Provides
    @Singleton
    fun provideMediaRecorder(): MediaRecorder {
        return  MediaRecorder()
    }
}


class HandleMeter @Inject constructor(val mRecorderFromDI: MediaRecorder): IHandleMeter {

    override fun getMSoundDensity(): Flow<MSoundDensity> {
      val temp = mRecorderFromDI.maxAmplitude
       ...
    }
}

CodePudding user response:

  1. You can create the instance manually and you can also get that from your Dependency injection. There is no difference as both will return a new instance.

  2. No, the instance is not recreated by Dependency injection when you do mRecorder = MediaRecorder(). You actually lose reference to initial instance created by dependency injection and get a new instance of MediaRecorder() assigned to mRecorder.

  • Related