본문으로 건너뛰기

Sample

Sync SDK는 양방향 동기화 기능을 통해 local 애플리케이션 및 remote 애플리케이션 간에 데이터를 실시간으로 공유하고 일관되게 유지할 수 있습니다. 개발자가 database 및 document 이름을 알고 있다면, 여러 애플리케이션 및 Android 컴포넌트 간에 데이터를 빠르고 쉽게 공유할 수 있습니다.

Profile database에 다음과 같은 데이터가 있을 때, SyncDatabase와 SyncDocument를 이용하여 데이터를 변경하고 동기화 할 수 있습니다.

Profile database
{
"id": "john@example.com",
"name": "John",
"age": 30,
"isMale": true,
"contact": {
"phone": "+82-10-1234-5678",
"github": "https://github.com/john",
"linkedin": "https://www.linkedin.com/in/john",
"address": {
"street": "123 Main St",
"city": "Seoul",
"country": "South Korea"
}
},
"skills": [
{
"name": "Java",
"proficiency": "Expert"
},
{
"name": "Kotlin",
"proficiency": "Advanced",
}
]
}

Profile 데이터를 전달 받기 위한 데이터 클래스를 정의합니다.

data class Profile(
val id: String,
val name: String,
val age: Int,
val isMale: Boolean,
val contact: Contact,
val skills: List<Skill>
)

data class Contact(
val phone: String,
val github: String,
val linkedin: String,
val address: Address
)

data class Address(
val street: String,
val city: String,
val country: String
)

data class Skill(
val name: String,
val proficiency: String,
)

SyncDatabase를 초기화한 후, SyncDocument를 통해 데이터를 읽고 쓰며, 변경된 데이터를 실시간으로 수신합니다.

lifecycleScope.launch {
val configsProvider = SyncConfigsProvider.createFromConfigFile(applicationContext).getOrThrow()

SyncDatabase.initialize(application, configsProvider) {
if (it.isReady()) {
// handle success
syncDatabase = SyncDatabase.getInstance("Profile")!!
} else {
// handle failure
val connectionState = it["Profile"]
Log.d("Sync SDK", connectionState?.reason ?: "unknown reason")
}
}
}

val document = syncDatabase.document("john@example.com")
document.addDocumentEventListener(object : DocumentListener {
override fun onDocumentChanged(document: SyncDocument,fromRemote: Boolean) {
// handle changes
val profile: Profile? = document.value()
val jsonString: String? = document.jsonString
}

override fun onDocumentError(document: SyncDocument, e: SyncError) {
// handle error
}
})

document.child("contact").setKeyValue("+82-10-8765-4321", "phone")
val phone = document.child("contact").child("phone").value<String>()
/*
"phone": +82-10-8765-4321"
*/

val addrDocument = document.paths("contact", "address")
addrDocument.setKeyValue("742 Evergreen Terrace", "street")
val street = addrDocument.child("street").value<String>()
/*
"street": "742 Evergreen Terrace"
*/

val android = Skill(name = "Android", proficiency = "Expert")
document.child("skills").insertToArray(0, android)
/*
"skills": [
{
"name": "Android",
"proficiency": "Expert"
},
{
"name": "Java",
"proficiency": "Expert"
},
{
"name": "Kotlin",
"proficiency": "Advanced",
}
]
*/