将kotlin数据类作为文档保存到Google Cloud Firestore

时间:2017-11-27 11:28:48

标签: serialization kotlin google-cloud-firestore

我有这个数据类

data class TripEntity(@Exclude val id: String = "", val name: String = "", val totalDistance: Long = 0, val startDate: Date?, val endDate: Date?)

然后我有这些方法来保存数据

private fun writeNewTripEntity(tripEntity: TripEntity, emitter: ObservableEmitter<TripEntity>) {
    val tripCollection = FirebaseFirestore.getInstance().collection("users/test/trips");
    tripCollection.add(tripEntity).addOnSuccessListener({ documentReference ->
        onWriteEntitySuccess(documentReference, emitter, tripEntity)
    }).addOnFailureListener({ e ->
        onWriteEntityError(e, emitter)
    })
}

private fun onWriteEntitySuccess(documentReference: DocumentReference, emitter: ObservableEmitter<TripEntity>, tripEntity: TripEntity) {
    Timber.log(Log.DEBUG, "TripEntity saved to FireBase successfully: " + documentReference.toString())
    emitter.onNext(TripEntity(documentReference.id, tripEntity.name, tripEntity.totalDistance, tripEntity.startDate, tripEntity.endDate))
    emitter.onComplete()
}

private fun onWriteEntityError(e: Exception, emitter: ObservableEmitter<TripEntity>) {
    Timber.e("Data could not be saved: %s", e.message)
    emitter.onError(e)
}

然后该文档将保留在Firestore中,但不会排除该ID,因为它应该符合Firestore文档。

Document screenshot

感谢您的帮助。

0 个答案:

没有答案