How to Setup a Room DB for Kotlin Multiplatform Compose

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hey guys and welcome back to a new video room is finally available for cotland multiplatform and in this video I will give you a quick introductory guide and how you can set that up for your cotton multiplatform project and have a shared database that works exactly like room with annotations with a dow so in case you already have a native Android project that uses room and you want to migrate that to Cotton multiplatform you are now one step closer to that and in fact the demo project I will create here is a composed multiplatform project so also one that shares the UI between IOS and Android and in order to create such a composed multiplatform product you need to go to km. jetbrains docomo inbuilt Wizard yet in Android studio um that allows us to create a composed multiplatform project but uh J print offers this wizard where we can enter a project name a package name take the platforms that we want to work on so in this case Android and iOS you could also add desktop web and server but we will be fine with Android and iOS you can download this that will be a zip file you need to extract and the folder that you extracted is the empty blind project you can then paste in your Android Studio project folder and then open that in Android studio and this is how it will look like so we will have one compos App application module we will have some Gradle scripts by default and the first thing we want to do is we want to add the necessary dependencies to Gradle we already have a version catalog so let's open lips. verions and here we now need to add room and I will just paste these versions so you can just write these off or also copy paste them from my GitHub repository Down Below on the one hand we have a room version which needs to be exactly that one so starting from alpha 01 from so 2.7.0 Alpha 01 starting from that version it supports cotton multiplatform we then want to use KSP so the code generation that room relies on for cartet version 1.9.2 3 and we will use an SQ light version which is the database framework that room is built on top of we also want to make sure that we are using the cotton version 1.9.2 3 which seems to be the case so that is the default version that um the wizard creates when we download the project at this point so we can go ahead and add our room Library so the actual dependency reference down here those are four dependencies on the one hand the normal room runtime which now works for cotton multiplatform we have the room runtime for Android so the Android implementation specifically since it differs a little bit how we need to create such a database reference on each platform we have the room compiler so what we need to um Implement with KSP we have SQ light bundles so the database driver that this room database runs on and lastly we can paste our Gradle plugins on the one hand as I said KSP for code generation and the room plugin which um creates some schemas generates helper code for our um for database deals with Auto migrations and all that stuff one more thing we need to do in order to make this run is we need to go to grader properties and we need to add this line here so Cartland native disabl compal Damon this is just something that um currently needs to be set to true because of um a bug or um otherwise there could be a crash issue that's something they communicate that way in their docks I don't know the the exact reason why this needs to needs to be enabled but it's something we need to do and then we can hit sync now now that we have these dependency references at least in our version catalog the next step is to also add them to our project so here we have our grad file for the compos app module which includes all of our dependencies and here we can now apply all that on the one hand for our Gradle plugins so we can say Alias um we want to include the lips plugins. KP on the one hand and our room compiler plugin uh grad plugin then we can scroll down to our common main dependencies so those dependencies that we want to include in our shared code section here we want to have an implementation lips room runtime on the one hand runtime and we want to have lips ascite bundled then we also need to add the KSP room compiler which doesn't work here inside of this dependencies block because here we have a little bit of a different uh dependency Handler so here you will notice if we have KSP and we say lips room compiler that one work I'm also not after syncing let's do that you will notice okay we actually get an arror because we can't apply KSP here but we can very well apply this by having a dedicated dependencies block down here let's open this here we have KSP lips room compiler we also need to define a schema directory so just a directory where room will put our database schemas when we when we have migrations where it will save the information for that we can do this with the room block um don't worry that it will mark this as an error right now because we haven't sck this successfully yet but in here we can set a schema directory which should be our project directory and new schemas directory inside that we can then try again hopefully this sync should now be successful that is looking so all right you can see the errors are going away case p is recognized and our dependencies also seem to be available so the next step is to find find our database schema so I want to just have a little people table here where we save some people let's do that in compose app common main so or shared code section that is now the magic power that room Works inside that shared code section let's actually also switch to the project view that's a little bit better here open compose app Source common main open the cotton Source set and in here let's create a new directory called database and inside that I will first of all create our person entity so in the end our table make that a data class and this now works really just the same as for Android we need to annotate this with entity and in here we need to give this maybe a name so every single person has a name and has an ID so let's keep this database table really simple just for the demo that you know how to implement this in a KMP project we have an ID so primary key which is zero by default so we want room to actually Auto generate these and we can do this by annotating this with primary key and setting autogenerate to True importing oops primary key and that is already our database table next step is to create our Dow our data access object in which we Define those functions we actually want to have in order to interact with our database so to insert something to delete something to query data let's also do that here so we have a people da macd that interface which we annotate with Dow then here let's first of all yeah let's start with the get all function tap to complete import query we actually don't have a people class but just a singular person uh let's also call this get all people we then want to have an upsert function so to either insert or upsert something function upsert with a person I like this autoc completion and we would like to have no not get person by ID but rather a delete function delete and there we go delete person and we need to make sure that these are actually supen functions by the way so we want to use cotin and here for getting all people I also want to get that as a flow so let's wrap this result inside of a flow but then we already have our Dow so here with this flow we're notified about um new emissions whenever our database changes so when we delete a person then this function will emit the new list of people and lastly what we need for a room database to make it work is a database class we can do this here in our package again call this people database make that a class it needs to be an abstract class which needs to inherit from room database needs to be annotated with ADD database to let room know that we're dealing with a database here and then we need to specify our entities as a list and here we have no not people class but person double colon class and we need to specify a version which is one uh if we have some kind of migrations later on we would need to increase that version so that room knows okay there's actually a new version I need to run some migrations and so on and lastly in here we need a people da which works really well with this Auto completion all right now that we have the very basic setup for our database we also need to find out how we can create an instance of this people database so we can in the end use it in our code and show a list of people creating this instance is a bit different on iOS compared to Android so on Android we need to use a context reference order to create a database instance while on iOS there is no such concept of a context so um it works a little bit differently there in order to create this instance exclusively for Android we need to jump into our Android main souret which is our Android save area where we have access to all Android specific dependencies and therefore also to the context we can open this here and in here let's yeah let's also have a database package inside inside that room um CMP package and then we have a get people database function so that will just be a plain coton file with a get people database high level function we make that return a people database and it needs a context reference which we very well have here inside of our Android main module all right in here we first of all need to specify a DB file so the file where our database gets saved to and you can see the AI already suggests exactly what I want so we use context get database path and call the people DB and then no we don't want to return people database oops um but rather return our room. database Builder pass in our context. application context and the name of our database should be our DB file and we take the absolute path of that then we can configure this a little bit more oh we also need to specify the type of DB we have here so people database and then we say we set the driver to our bundled SQ light driver which we've in included with a dependency and then we can call build and that's how we create a database reference now on KMP for the Android side let's now also find out how we can do this for iOS let's oh let's not copy this let's go to iOS main so our iOS save area and in here we also create a database directory and inside this database directory we have a get people database function function get people database this does not take any arguments on iOS that's a bit simpler in here we also need to specify a DB file which can be NS home directory so the iOS equivalent to the home directory of the app to the internal storage and then we say okay we actually add our people DB to the end of that path and then we can say return room database Builder again make that a people database give this a name of our DB file which is already a string and we need to specify a factory so that is a bit different compared to Android and this DB Factory needs to be created uh quite weird so here we need to say people database double colon class that instantiate implementation this function um will be generated after rebuilding it also happened to me that this stood in red even after rebuilding uh but you will notice that when we launch our app uh it will actually run without any issues so don't be confused that this is marked as an error let's also just set the driver here to a bundled SQ light driver build this and then we are ready to go so now that we are able to create a database we need to also make use of that and display it in our UR our UI in a composed multiplatform project is located in this app KT file here in our common source set let's open that there is some default code let's actually get rid of all of that and Define our UI here first of all we want to pass our people Dow here so we can make use of that here in our code we can observe all people buy people Dow get all collect estate that is almost correct we just called it get all people and we can work with that then let's also get a reference to a ctin scope that is aware of the current composition since we will need this to execute functions of this Dow and as a first step we open the launch effect true block here just to have something really simple where we can insert some entries into our database so we actually see if that works so let's have a people list in here so just a list of people we want to insert we have a person give this a name of I don't know John that we have Alis and Philip something like this and then we can Loop over this list so we say people list for each and we just take our people da upsert and we insert this person and if that already exists with the specific ID this function would just update the existing entry all right now we have some entries in our database the next step is that we actually show this in a little lazy column so we have a lazy column add a modifier fill Max size give this maybe some content padding of pading values 16 TP there we go import both that and then in here we have an items block where we Loop over our people get a reference to every single person inside that list and then we have a text that displays its name so the text is person. name and we can say okay we have a modifier of filmax WID and we give it some padding of 160p in between let's just make this a clickable modifier so we can also delete a person um just to have a very simplified way uh here we need to launch a CO routine in our scope and then call our people da delete and we want to delete this current person we clicked on and that's already our very simple UI we now of course need to pass this people down to this application composable let's take a look at where we call this by holding command and clicking on that on the one hand our main activity and in our main view controller so in here we have our iOS compos UI view controller repper which uh translates our composable into the iOS World kind of and here we can create our Dow by saying is equal to remember and we create our database reference with get people database and refer to the people Dow I have to say this is of course a very simplified example of how we get reference to a DA of course in real project I would use some sort of dependency injection setup uh that we really make sure that we have a Singleton here for this database instance and then inject this from a safe place from a safe module but just for for for quick demo I wanted to create this here directly inside the composable so we can pass it to our application composable then we can jump into main activity so that is the Android side of things here we also need to pass this Dow and I want to get rid of the preview here and let's just create the Dow here again doing this in uh the oncreate function of main activity would be terrible in the real app since it would be recreated after configuration changes but we want to see how this works on KMP so we can say get people database need to pass in the context and we can just say Okay application context we then pass it down here and we need to refer to the people Dow like this and I think that should be everything we need so I've connected my device and we try this out first of all Android and then we of course also want to see if this works on iOS and we do get a little KSP error let's take a look uh there is a problem with the query SQL error or missing database no such table people because it's called person right let's take a look in people Dow ah there we go this needs to be person uh there is no Auto completion here so that is something that's a bit different compared to normal Android but let's let's relaunch this and see if it now works there we go and we see our people we can also confirm this by opening the database inspector um here with more tool windows and then opening app inspection and then selecting the process after waiting a little moment no apparently Android Studio does not like to attach my apps process but I verified that before that you can definitely inspect your room database here as well um I would probably need to invalidate cashes here um but you can believe me that this works I've also relaunched the app still doesn't work but we can of course rotate our app survive screen rotations since it's of course persistent and if we click on an entry then we delete it exactly what we implemented so far if we then relaunch it uh that's the best way to test it we should have John Phillip and then our three more and new entries and there we go that's exactly what happens all right but we also want want to test this on iOS so far this is nothing new to how room works on Native Android but how do we launch this on iOS so we need to make sure that we go instead of a product hokey find our IOS app folder open that then you will find an IOS app X code project open that as well and then you'll find this xcode workspace file here we want to right click open that in xcode and then an ax code window will open up there we go and then we can just make sure that we switch to some kind of emulator here maybe let's choose the iPhone 14 pro and hit run so we don't need to do any adjustments in xcode that's the very cool thing about compos multiplatform let's wait until this builds and hopefully the build succeeds and we get to see our app in here yep it finished building there we go and we see our three people awesome it also works on iOS we can of course also delete people here by clicking on them and if we then relaunch we will see that it's really persistent storage so we um only remain with philli and then we add our three new people after a successful relaunch Isn't that cool slowly KMP is really going somewhere I think it's really promising and I'm very much looking forward to its future and if you are an Android developer or a KMP developer and you just feel like okay there is so much out there are so many different Technologies and you understand them you know how to implement such a room database but you really struggle to to glue things together you really don't know how to really build a scaling app with good architecture that is testable you don't know how to write test cases for that and you just feel a little bit lost then I will put a link down below where you can apply to my 10we mentorship program where we will work together really closely over the course of 10 weeks I will provide code reviews you can ask me anything you like 7 days a week and we will work on your technical struggles really really closely you can apply for free down below in case you seem to be a fit we will hop into 50-minute call with each other where we talk about all the details and if both of us then still say that sounds like a fit we will make it fix awesome thanks so much for watching have an amazing rest of your week see you back in the next video bye-bye
Info
Channel: Philipp Lackner
Views: 10,378
Rating: undefined out of 5
Keywords:
Id: IHs0yPa2Nv4
Channel Id: undefined
Length: 20min 26sec (1226 seconds)
Published: Sun May 19 2024
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.