在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
开源软件名称(OpenSource Name):realm/realm-kotlin开源软件地址(OpenSource Url):https://github.com/realm/realm-kotlin开源编程语言(OpenSource Language):Kotlin 93.6%开源软件介绍(OpenSource Introduction):Realm is a mobile database that runs directly inside phones, tablets or wearables. It allows synchronization of data between devices using Atlas App Services and Device Sync. This repository holds the source code for the Kotlin SDK for Realm, which runs on Kotlin Multiplatform and Android. General AvailabilityThe Realm Kotlin SDK is GA. Documentation can be found here. Sample projects can be found here. If you are upgrading from a previous beta release of Realm Kotlin, please see the CHANGELOG for the full list of changes. If you are migrating from Realm Java, please see the Migration Guide. UsageInstallationInstallation differs slightly depending on the type of project and whether or not you are using Device Sync. See the details in the documentation: Define modelStart writing your database logic by first defining your model. class Person : RealmObject {
var name: String = "Foo"
var dog: Dog? = null
}
class Dog : RealmObject {
var name: String = ""
var age: Int = 0
} Open DatabaseDefine a RealmConfiguration with the database schema, then open the Realm using it. // use the RealmConfiguration.Builder() for more options
val configuration = RealmConfiguration.create(schema = setOf(Person::class, Dog::class))
val realm = Realm.open(configuration) WritePersist some data by instantiating the model object and copying it into the open Realm instance. // plain old kotlin object
val person = Person().apply {
name = "Carlo"
dog = Dog().apply { name = "Fido"; age = 16 }
}
// Persist it in a transaction
realm.writeBlocking { // this : MutableRealm
val managedPerson = copyToRealm(person)
}
// Asynchronous updates with Kotlin coroutines
CoroutineScope(context).async {
realm.write { // this : MutableRealm
val managedPerson = copyToRealm(person)
}
} QueryThe query language supported by Realm is inspired by Apple’s NSPredicate, see more examples here // All persons
import io.realm.kotlin.ext.query
val all = realm.query<Person>().find()
// Persons named 'Carlo'
val personsByNameQuery: RealmQuery<Person> = realm.query<Person>("name = $0", "Carlo")
val filteredByName: RealmResults<Person> = personsByNameQuery.find()
// Person having a dog aged more than 7 with a name starting with 'Fi'
val filteredByDog = realm.query<Person>("dog.age > $0 AND dog.name BEGINSWITH $1", 7, "Fi").find()
// Observing changes with Coroutine Flows
CoroutineScope(context).async {
personsByNameQuery.asFlow().collect { result: ResultsChange<Person> ->
println("Realm updated: Number of persons is ${result.list.size}")
}
} Update// Find the first Person without a dog
realm.query<Person>("dog == NULL LIMIT(1)")
.first()
.find()
?.also { personWithoutDog ->
// Add a dog in a transaction
realm.writeBlocking {
findLatest(personWithoutDog)?.dog = Dog().apply { name = "Laika"; age = 3 }
}
} DeleteUse the result of a query to delete from the database. // delete all Dogs
realm.writeBlocking {
// Selected by a query
val query = this.query<Dog>()
delete(query)
// From a query result
val results = query.find()
delete(results)
// From individual objects
results.forEach { delete(it) }
} Observing data changesRealm support asynchronous observers on all its data structures. RealmA Realm can be observed globally for changes on its data. realm.asFlow()
.collect { realmChange: RealmChange<Realm> ->
when (realmChange) {
is InitialRealm<*> -> println("Initial Realm")
is UpdatedRealm<*> -> println("Realm updated")
}
} RealmObjectRealm objects can be observed individually. A list of the changed field names is provided on each update. person.asFlow().collect { objectChange: ObjectChange<Person> ->
when (objectChange) {
is InitialObject -> println("Initial object: ${objectChange.obj.name}")
is UpdatedObject ->
println("Updated object: ${objectChange.obj.name}, changed fields: ${objectChange.changedFields.size}")
is DeletedObject -> println("Deleted object")
}
} RealmListsRealm data structures can be observed too. On person.addresses.asFlow()
.collect { listChange: ListChange<String> ->
when (listChange) {
is InitialList -> println("Initial list size: ${listChange.list.size}")
is UpdatedList ->
println("Updated list size: ${listChange.list.size} insertions ${listChange.insertions.size}")
is DeletedList -> println("Deleted list")
}
} RealmQueryQuery results are also observable, and like realm.query<Person>().asFlow()
.collect { resultsChange: ResultsChange<Person> ->
when (resultsChange) {
is InitialResults -> println("Initial results size: ${resultsChange.list.size}")
is UpdatedResults ->
println("Updated results size: ${resultsChange.list.size} insertions ${resultsChange.insertions.size}")
}
} RealmSingleQuerySingle element queries allow observing a realm.query<Person>("name = $0", "Carlo").first().asFlow()
.collect { objectChange: SingleQueryChange<Person> ->
when (objectChange) {
is PendingObject -> println("Pending object")
is InitialObject -> println("Initial object: ${objectChange.obj.name}")
is UpdatedObject ->
println("Updated object: ${objectChange.obj.name}, changed fields: ${objectChange.changedFields.size}")
is DeletedObject -> println("Deleted object")
}
} Next: head to the full KMM example. Using SnapshotsIf you want to test recent bugfixes or features that have not been packaged in an official release yet, you can use a -SNAPSHOT release of the current development version of Realm via Gradle, available on Maven Central
See Config.kt for the latest version number. Kotlin Memory Model and Coroutine compatibilityRealm Kotlin is implemented against Kotlin's default memory model (the old one), but still supports running with the new memory model if enabled in the consuming project. See https://github.com/JetBrains/kotlin/blob/master/kotlin-native/NEW_MM.md#switch-to-the-new-mm for details on enabled the new memory model. By default Realm Kotlin depends and requires you to run with Kotlin Coroutines version
See https://github.com/JetBrains/kotlin/blob/master/kotlin-native/NEW_MM.md#unexpected-object-freezing for more details. ContributingSee CONTRIBUTING.md for more details! Code of ConductThis project adheres to the MongoDB Code of Conduct. By participating, you are expected to uphold this code. Please report unacceptable behavior to [email protected]. LicenseRealm Kotlin is published under the Apache 2.0 license. This product is not being made available to any person located in Cuba, Iran, North Korea, Sudan, Syria or the Crimea region, or to any other person that is not eligible to receive the product under U.S. law. |
2023-10-27
2022-08-15
2022-08-17
2022-09-23
2022-08-13
请发表评论