Search code examples
androidkotlinretrofitandroid-room

In Android, Room and Retrofit doesn't support KMP, what should I use instead?


I have an Android project that I would like to make a KMP project so I can run it on iOS as well, I'm using Room and Retrofit libraries but seems like they don't support KMP because they generate Java code, is there a way to fix that? and if not, what should I use instead and how to use a different DB library without losing the preserved data?


Solution

  • Unfortunately, there is no way to make them work, unless you use different libraries for iOS and keep these 2 on the Android side only.

    As an alternative, I can recommend using Ktor instead of Retrofit, as it's a pure kotlin library, and the transition is quite easy, especially if your app is using clean architecture and the data layer is separated from the other layers.

    For database management you can use SQLDelight instead of Room, it's not as intuitive as Room and can be a little bit harder to get used to, but it's a great alternative, the transition requires doing multiple steps, mainly because you will have to make sure everything is exactly the same as it was so you can keep the stored data and not lose it.

    Notes to not lose the data after migration

    1. Make sure to use the exact same schema
    2. Make sure to use the exact same db file name in SQLDelight as it was in Room
    3. Write migration files for all the versions you migrated from previously, just like in Room manual migration, and if you used Room AutoMigration method, then write a manual migration for it in SQLDelight.

    Note: No.3 is important to keep backward compatibility, otherwise, users that have a DB version older than the latest won't be able to use your app.

    Step by step

    If you decide to do it, I wrote a detailed article step by step about migrating from Room to SQLDelight without losing the saved data, hope that helps!