Cleaned up code for Contact sync

This commit is contained in:
Moez Bhatti
2017-12-21 21:24:35 -05:00
parent 84c887a44d
commit 5aeec5c139
2 changed files with 19 additions and 24 deletions
@@ -2,10 +2,17 @@ package com.moez.QKSMS.common.util.extensions
import io.reactivex.Observable
import io.realm.Realm
import io.realm.RealmModel
import io.realm.RealmObject
import io.realm.RealmResults
fun RealmObject.insertOrUpdate() {
fun RealmModel.insertOrUpdate() {
val realm = Realm.getDefaultInstance()
realm.executeTransaction { realm.insertOrUpdate(this) }
realm.close()
}
fun <T : RealmModel> Collection<T>.insertOrUpdate() {
val realm = Realm.getDefaultInstance()
realm.executeTransaction { realm.insertOrUpdate(this) }
realm.close()
@@ -2,9 +2,10 @@ package com.moez.QKSMS.domain.interactor
import android.content.Context
import com.moez.QKSMS.common.util.extensions.asFlowable
import com.moez.QKSMS.common.util.extensions.insertOrUpdate
import com.moez.QKSMS.data.mapper.CursorToContact
import com.moez.QKSMS.data.model.Contact
import io.reactivex.Flowable
import io.realm.Realm
import timber.log.Timber
import java.util.concurrent.TimeUnit
import javax.inject.Inject
@@ -12,24 +13,15 @@ import javax.inject.Inject
open class ContactSync @Inject constructor(
private val context: Context,
private val cursorToContact: CursorToContact)
: Interactor<Unit, Long>() {
: Interactor<Unit, List<Contact>>() {
override fun buildObservable(params: Unit): Flowable<Long> {
override fun buildObservable(params: Unit): Flowable<List<Contact>> {
val contentResolver = context.contentResolver
var realm: Realm? = null
var startTime = 0L
Timber.v("Starting contact sync")
val startTime = System.currentTimeMillis()
return Flowable.just(params)
.doOnNext {
Timber.v("Starting contact sync")
startTime = System.currentTimeMillis()
// We need to set up realm on the io thread, and doOnSubscribe doesn't support setting a custom Scheduler
realm = Realm.getDefaultInstance()
realm?.beginTransaction()
}
.flatMap { contentResolver.query(CursorToContact.URI, CursorToContact.PROJECTION, null, null, null).asFlowable() }
return contentResolver.query(CursorToContact.URI, CursorToContact.PROJECTION, null, null, null).asFlowable()
.map { cursor -> cursorToContact.map(cursor) }
.groupBy { contact -> contact.lookupKey }
.flatMap { group -> group.toList().toFlowable() }
@@ -42,15 +34,11 @@ open class ContactSync @Inject constructor(
}
.toList().toFlowable()
.doOnNext { contacts ->
Timber.v("${contacts.size} contacts")
realm?.insertOrUpdate(contacts)
contacts.insertOrUpdate()
val duration = TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis() - startTime)
Timber.v("Synced contacts in $duration seconds")
}
.doOnNext {
realm?.commitTransaction()
realm?.close()
Timber.v("Synced contacts in ${TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis() - startTime)} seconds")
}
.map { 0L }
}
}