Last active
October 8, 2020 13:20
-
-
Save yusufceylan/307c3c07e4d260b6fa28fbb27a86ccd3 to your computer and use it in GitHub Desktop.
Cloud DB live data changes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@ExperimentalCoroutinesApi | |
suspend fun getUserDataChanges(id : String?) : Flow<Resource<User>> = withContext(ioDispatcher) { | |
callbackFlow { | |
if (id == null) { | |
offer(Resource.Error(Exception("Id must not be null"))) | |
return@callbackFlow | |
} | |
// 1- Create query | |
val query: CloudDBZoneQuery<User> = CloudDBZoneQuery.where(User::class.java).equalTo("accountId", id) | |
// 2 - Register query | |
val subscription = cloudDBZone.subscribeSnapshot(query, CloudDBZoneQuery.CloudDBZoneQueryPolicy.POLICY_QUERY_FROM_CLOUD_PRIOR, object : OnSnapshotListener<User> { | |
override fun onSnapshot(snapShot: CloudDBZoneSnapshot<User>?, error: AGConnectCloudDBException?) { | |
// Check error | |
if (error != null) { | |
error.printStackTrace() | |
offer(Resource.Error(error)) | |
return | |
} | |
// Check data | |
try { | |
val snapShotObjects = snapShot?.snapshotObjects | |
// Get user data from db | |
if (snapShotObjects != null) { | |
// Check item in db exist | |
if (snapShotObjects.size() == 0) { | |
offer(Resource.Error(Exception("User not exists in Cloud DB!"))) | |
return | |
} | |
while (snapShotObjects.hasNext()) { | |
val user : User = snapShotObjects.next() | |
offer(Resource.Success(user)) | |
} | |
} | |
} catch (e : Exception) { | |
e.printStackTrace() | |
offer(Resource.Error(e)) | |
} finally { | |
snapShot?.release() | |
} | |
} | |
}) | |
// 3 - Remove subscription | |
awaitClose { | |
subscription.remove() | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment