rafi0101 / Android-Room-Database-Backup

Simple tool to backup and restore your room database in Android
MIT License
241 stars 19 forks source link

Cannot use it with Koin #36

Open Borderliner opened 4 months ago

Borderliner commented 4 months ago

How do I utilize this library with Koin? Koin passes Application instead of ComponentActivity and it pops up errors. Here's my database module:

const val DATABASE_NAME = "app_database"
val databaseModule = module {
    single { provideRoomDatabase(androidContext()) }
    single { params -> provideRoomBackup(params.get(), get()) }
}

fun provideRoomDatabase(context: Context): Database {
    return Room.databaseBuilder(context, Database::class.java, DATABASE_NAME)
        .setJournalMode(RoomDatabase.JournalMode.TRUNCATE)
        .fallbackToDestructiveMigration()
        .build()
}

fun provideRoomBackup(context: Context, database: Database): RoomBackup {
    return RoomBackup(context)
        .database(database)
        .enableLogDebug(true)
        .backupIsEncrypted(true)
        .customEncryptPassword("asfagwsrhaerjhrtjr5j")
        .backupLocation(RoomBackup.BACKUP_FILE_LOCATION_INTERNAL)
        .maxFileCount(5)
        .apply {
            onCompleteListener { success, message, exitCode ->
                Timber.d("Backup", "success: $success, message: $message, exitCode: $exitCode")
            }
        }
}

And this is how I get the instance in my composable:

val ctx = LocalContext.current
val backupSystem: RoomBackup = koinInject { parametersOf(ctx) }

It fails with:

could not create instance for '[Singleton:'de.raphaelebner.roomdatabasebackup.core.RoomBackup']': java.lang.IllegalStateException: LifecycleOwner meshki.studio.negarname.ui.app.AppActivity@281e914 is attempting to register while current state is RESUMED. LifecycleOwners must call register before they are STARTED.

I'd appreciate it if you could provide a solution here or in readme file for Koin users.

rafi0101 commented 1 month ago

I'm sorry, I'm not familiar with Koin right now. But the error messages seem like a problem I had before. Maybe it's the same as in Kotlin, you need to initialize your RoomBackup instance outside of an onClicklistener or something where a new lifecycle starts. I have described it in the Properties section. Or have a look at my Kotlin examples: Activity and Fragment. Please let me know if this works for you and I apologize for the late reply.