Tool for accessing firebase realtime database
allprojects {
repositories {
...
maven { url 'https://jitpack.io' }
}
}
dependencies {
implementation 'com.github.dudziks:mdfirebase:v0.0.9'
}
data class MyDTO(var text: String)
data class MyModel(var name: String)
interface IMapper<DTO, Model> {
fun mapFromDTO(from: DTO?): Model?
fun mapToDTO(from: Model?): DTO?
}
// MyDTO - Entity
// MyModel - Model
class MyMapper: FirebaseMapper<MyDTO, MyModel>() {
override fun mapFromDTO(from: MyDTO?): MyModel? =
from?.run { MyModel(contents = text, theKey = key) }
override fun mapToDTO(from: MyModel?): MyDTO? =
from?.run { MyDTO(text = contents, key = theKey) }
}
Example of class using instance of IFirebaseDAO<MyDTO, MyModel>
class MyRepo {
private val dao: IFirebaseDAO<MyDTO, MyModel> = FirebaseDAO.Builder<MyDTO, MyModel>()
.fbUser(Firebase.auth.currentUser)
.rootNodePath { "path/to/my/data" }
.mapper(MyMapper())
.build()
@ExperimentalCoroutinesApi
fun getData(): Flow<MmyModel?> =callbackFlow {
dao.addListener(DefaultFirebaseDBCallback(
onAddedCallback = { offer(it) }
//onChangedCallback = { /* manage changed data */}
//onAddedListCallback = { /* manage changed data */}
//onRemovedCallback = { /* manage removed data */}
//onDataChangedCallback = { /* manage changed data */}
//onErrorCallback = { /* manage error */}
))
awaitClose { dao.removeListener()
}
}
You can override all the callbacks commented out. There are empty default implementation of each callback, so if you wont implement it, it will do nothing.
class MyViewModel: ViewModel() {
val myRepo = MyRepo()
val liveData = liveData(Dispatchers.IO) {
myRepo.getData().collect { value -> emit(value) }
}
}