Realm Object未更新

时间:2018-02-01 08:17:07

标签: android kotlin realm rx-java rx-java2

我在我的项目中使用Realm,我试图通过RxJava更新领域对象。 Realm对象已成功存储,但realm对象未更新。实际上我正在使用RxJava对UI线程和所有WRITE操作在后台线程上执行所有Read操作。下面是我执行所有Realm读写操作的代码。

class SuggestedFriendsController internal constructor(realm : Realm) {
private var realm: Realm? = null

init {
    this.realm = realm
}

fun addSuggestedFriends(requestPojo: RequestPojo?) {
    realm?.executeTransaction { realm ->
        val realmFriends = RealmSuggestedFriends()
        realmFriends.friendEmail = requestPojo?.email
        realmFriends.friendImage = requestPojo?.image
        realmFriends.friendName = requestPojo?.name
        realmFriends.friendStatus = requestPojo?.status
        realmFriends.friendThumbImage = requestPojo?.thumb_image
        realmFriends.friendUid = requestPojo?.uid
        realmFriends.requestSent = "No"
        realm.copyToRealmOrUpdate(realmFriends)
    }
}


fun getRequestStateSync(uid: String?): String? {
      var res =  Realm.getDefaultInstance().use { realm ->
          realm?.where(RealmSuggestedFriends::class.java)
              ?.equalTo("friendUid", uid)
              ?.findFirst()
      }
    return res?.requestSent
}

fun getAllAsync() = Observable.create<List<RealmSuggestedFriends>> { emitter ->
    Realm.getDefaultInstance().use { realm ->
        val results = realm?.where(RealmSuggestedFriends::class.java)
                ?.findAll()
        emitter.onNext(realm?.copyFromRealm(results)!!)
    }
}.flatMapIterable { list -> list }
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())

fun updateSuggestedFriendAsync(uid: String?, request_type: String?) =
        Single.create<String>{emitter ->
            Realm.getDefaultInstance().use {realm ->
                    realm?.executeTransaction{ realm ->
                        var suggested = realm.where(RealmSuggestedFriends::class.java)
                                .equalTo("friendUid", uid)
                                .findFirst()!!
                        suggested.requestSent = request_type
                        realm.insertOrUpdate(suggested)
                    }
                emitter.onSuccess("success")
                }
            }.observeOn(AndroidSchedulers.mainThread())
        .subscribeOn(Schedulers.io())

}

以下是我的活动代码。这里变量suggestedFriendController?.getRequestStateSync(friend_uid)值保持不变,即使其值在数据库中更改。

class SFriend : AppCompatActivity(){
private var image : NewCircularImagview ?= null
private var name : AppCompatTextView ?= null
private var addFriend : AppCompatButton ?= null
private var imageUrl : String ?= null
private var toolbar : Toolbar ?= null
private var toolbar_text : TextView ?= null
private var progressBar : ProgressBar ?= null
private var friend_uid : String ?= null
private var databaseReference: DatabaseReference? = null
private var uid: String? = null
private var compositeDisposable : CompositeDisposable ?= null
private var realm : Realm ?= null
private var suggestedFriendController : SuggestedFriendsController ?= null
private var request_state : String ?= null

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.suggested_friend_profile)
    initialize()
  friend_uid = intent.getStringExtra("friend_uid")
  imageUrl = intent.getStringExtra("imageurl")
  name?.text = intent.getStringExtra("name")
  request_state = suggestedFriendController?.getRequestStateSync(friend_uid)
    if (request_state?.equals("No")!!){
        addFriend?.setText("Send Request")
    }else{
        addFriend?.text = "Cancel Request"
    }
}
private fun initialize() {
compositeDisposable = CompositeDisposable()
databaseReference = FirebaseDatabase.getInstance().reference
databaseReference?.keepSynced(true)
uid = FirebaseAuth.getInstance().currentUser?.uid
progressBar = findViewById(R.id.progress_bar)
image = findViewById(R.id.profile_pic)
name = findViewById(R.id.name)
addFriend = findViewById(R.id.addFriend)
toolbar = findViewById(R.id.toolbar)
toolbar_text = toolbar?.findViewById(R.id.toolbar_text1)
toolbar_text?.visibility = View.VISIBLE
setSupportActionBar(toolbar)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
getSupportActionBar()?.setHomeButtonEnabled(true)
realm = Realm.getDefaultInstance()
suggestedFriendController = realm?.let { r-> SuggestedFriendsController(r) }
}

override fun onStart() {
    super.onStart()
    progressBar?.visibility = View.VISIBLE
    Picasso.with(this).load(imageUrl!!).into(image,object :Callback{
        override fun onSuccess() {
            progressBar?.visibility = View.GONE
        }

        override fun onError() {
            showMessage("image loading failed")
        }
    })
    addFriend?.setOnClickListener {
        addFriend?.isEnabled = false
        if (request_state?.equals("No")!!) {
            sendRequest(friend_uid)
        }else{
            cancelRequest(friend_uid)
        }
    }
}

private fun cancelRequest(friend_uid: String?) {
    Single.create<String>{ subscriber ->
        databaseReference
                ?.child("friend_requests")
                ?.child(uid)
                ?.child(friend_uid)
                ?.removeValue()
                ?.addOnCompleteListener { task ->
                    if (task.isSuccessful) {
                        if (!subscriber.isDisposed) {
                        subscriber.onSuccess("success")
                        }
                    }else{
                        subscriber.onError(Throwable("error in cancel request"))
                    }
                }
    }.subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .flatMap { Single.create<String>{ subscriber ->
                        databaseReference
                                ?.child("friend_requests")
                                ?.child(friend_uid)
                                ?.child(uid)
                                ?.removeValue()
                                ?.addOnCompleteListener { task ->
                                    if (task.isSuccessful){
                                        if (!subscriber.isDisposed){
                                            subscriber.onSuccess("success")
                                        }
                                    }else{
                                        subscriber.onError(Throwable("error in cancel request"))
                                    }
                                }
                     }.subscribeOn(Schedulers.io())
            }
            .subscribe({
                t1 -> showMessage(t1)
                addFriend?.text = "Send Request"
                addFriend?.isEnabled = true
                suggestedFriendController?.updateSuggestedFriend(friend_uid!!,"No")
            },{
                t2 -> showMessage(t2.message)
            })
}

private fun showMessage(message : String?) {
    Toast.makeText(this,message,Toast.LENGTH_SHORT).show()
}

private fun sendRequest(friend_uid : String?){
   var d =  Single.create<String>{ subscriber ->
                databaseReference
                ?.child("friend_requests")
                ?.child(uid)
                ?.child(friend_uid)
                ?.child("request_type")
                ?.setValue("sent")
                ?.addOnCompleteListener { task ->
                    if (task.isSuccessful){
                        if (!subscriber.isDisposed){
                            subscriber.onSuccess("success")
                        }
                    }else{
                        subscriber.onError(Throwable("request failed"))
                    }
                }
    }.subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .flatMap { Single.create<String> { subscriber ->
                databaseReference
                        ?.child("friend_requests")
                        ?.child(friend_uid)
                        ?.child(uid)
                        ?.child("request_type")
                        ?.setValue("received")
                        ?.addOnCompleteListener { task ->
                            if (task.isSuccessful){
                                if (!subscriber.isDisposed){
                                    subscriber.onSuccess("sent")
                                }
                            }else{
                                subscriber.onError(Throwable("request failed"))
                            }
                        }
                }.subscribeOn(Schedulers.io())
            }.flatMap {
       suggestedFriendController?.updateSuggestedFriendAsync(friend_uid,"Yes")
   }.subscribe({
      t1: String? -> showMessage(t1)
        addFriend?.text = "Delete Request"
        addFriend?.isEnabled = true
    },{
        t2 -> showMessage(t2.message)
    }
    )
   compositeDisposable?.add(d)
}

override fun onBackPressed() {
    super.onBackPressed()
    finish()
}

override fun onStop() {
    super.onStop()
    compositeDisposable?.clear()
}

override fun onDestroy() {
    super.onDestroy()
    realm?.close()
}

}

下面的代码是我的Realm模型。

open class RealmSuggestedFriends : RealmObject(){
@Required
@PrimaryKey
var friendUid : String ?= null

@Required
var friendName : String ?= null

@Required
var friendEmail : String ?= null

@Required
var friendStatus : String ?= null

@Required
var friendImage : String ?= null

@Required
var friendThumbImage : String ?= null

@Required
var requestSent : String ?= null
}

我需要你的建议才能让它发挥作用。帮帮我

1 个答案:

答案 0 :(得分:1)

不要获取String,获取对象。此外,我不会将Realm实例传递给类似的构造函数。

class SuggestedFriendsController {

    fun addSuggestedFriends(requestPojo: RequestPojo) {
        Realm.getDefaultInstance().use { r ->
            {
                r.executeTransaction { realm ->
                    realm.insertOrUpdate(RealmSuggestedFriends().apply {
                        friendEmail = requestPojo?.email
                        friendImage = requestPojo?.image
                        friendName = requestPojo?.name
                        friendStatus = requestPojo?.status
                        friendThumbImage = requestPojo?.thumb_image
                        friendUid = requestPojo?.uid
                        requestSent = "No"
                    })
                }
            }
        }


        fun getSuggestedFriend(realm: Realm, uid: String): RealmSuggestedFriends? =
            realm.where<RealmSuggestedFriends>().equalTo("friendUid", uid).findFirst()

        fun getAllAsync() = Single.create<List<RealmSuggestedFriends>> { emitter ->
            Realm.getDefaultInstance().use { realm ->
                with(realm) {
                    emitter.onNext(copyFromRealm(where<RealmSuggestedFriends>().findAll())
                }
            }
        }.subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())

        fun updateSuggestedFriendAsync(uid: String, requestType: String) =
            Single.create<String> { emitter ->
                Realm.getDefaultInstance().use { r ->
                    r.executeTransaction { realm ->
                        var suggested = realm.where<RealmSuggestedFriends>()
                            .equalTo("friendUid", uid)
                            .findFirst()!!
                        suggested.requestSent = requestType
                        realm.insertOrUpdate(suggested)
                    }
                    emitter.onSuccess("success")
                }
            }.subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())

    }

    class SFriend : AppCompatActivity() {
        private lateinit var image: NewCircularImagview
        private lateinit var name: AppCompatTextView
        private lateinit var addFriend: AppCompatButton
        private lateinit var imageUrl: String
        private lateinit var toolbar: Toolbar
        private lateinit var toolbar_text: TextView
        private lateinit var progressBar: ProgressBar
        private lateinit var friend_uid: String
        private lateinit var databaseReference: DatabaseReference
        private lateinit var uid: String
        private lateinit var compositeDisposable: CompositeDisposable
        private lateinit var realm: Realm
        private lateinit var suggestedFriendController: SuggestedFriendsController
        private var suggestedFriend: RealmSuggestedFriends

        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            setContentView(R.layout.suggested_friend_profile)
            initialize()
            friend_uid = intent.getStringExtra("friend_uid")
            imageUrl = intent.getStringExtra("imageurl")
            name.text = intent.getStringExtra("name")
            suggestedFriend = suggestedFriendController.getRequestStateSync(realm, friend_uid)
            addFriend.text = when {
                "No" == suggestedFriend?.requestSent -> "Send Request"
                else ->
                    = "Cancel Request"
            }
            suggestedFriend.addChangeListener(RealmChangeListener {
                if(it.isValid()) {
                     addFriend.text = when {
                         "No" == it.requestSent -> "Send Request"
                         else -> "Cancel Request"
                     }
                }
            })
        }

        private fun initialize() {
            compositeDisposable = CompositeDisposable()
            databaseReference = FirebaseDatabase.getInstance().reference
            databaseReference.keepSynced(true)
            uid = FirebaseAuth.getInstance().currentUser?.uid
            progressBar = findViewById(R.id.progress_bar)
            image = findViewById(R.id.profile_pic)
            name = findViewById(R.id.name)
            addFriend = findViewById(R.id.addFriend)
            toolbar = findViewById(R.id.toolbar)
            toolbar_text = toolbar?.findViewById(R.id.toolbar_text1)
            toolbar_text.visibility = View.VISIBLE
            setSupportActionBar(toolbar)
            supportActionBar!!.setDisplayHomeAsUpEnabled(true)
            supportActionBar!!.setHomeButtonEnabled(true)
            realm = Realm.getDefaultInstance()
            suggestedFriendController = SuggestedFriendsController()
        }

        override fun onStart() {
            super.onStart()
            progressBar.visibility = View.VISIBLE
            Picasso.with(this).load(imageUrl).into(image, object : Callback {
                override fun onSuccess() {
                    progressBar.visibility = View.GONE
                }

                override fun onError() {
                    showMessage("image loading failed")
                }
            })
            addFriend.setOnClickListener {
                addFriend.isEnabled = false
                if ("No" == suggestedFriend?.requestSent) {
                    sendRequest(friend_uid)
                } else {
                    cancelRequest(friend_uid)
                }
            }
        }

        private fun cancelRequest(friend_uid: String?) {
            Single.create<String> { subscriber ->
                databaseReference
                    .child("friend_requests")
                    .child(uid)
                    .child(friend_uid)
                    .removeValue()
                    .addOnCompleteListener { task ->
                        if (task.isSuccessful) {
                            if (!subscriber.isDisposed) {
                                subscriber.onSuccess("success")
                            }
                        } else {
                            subscriber.onError(Throwable("error in cancel request"))
                        }
                    }
            }.subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .flatMap {
                    Single.create<String> { subscriber ->
                        databaseReference
                            .child("friend_requests")
                            .child(friend_uid)
                            .child(uid)
                            .removeValue()
                            .addOnCompleteListener { task ->
                                if (task.isSuccessful) {
                                    if (!subscriber.isDisposed) {
                                        subscriber.onSuccess("success")
                                    }
                                } else {
                                    subscriber.onError(Throwable("error in cancel request"))
                                }
                            }
                    }.subscribeOn(Schedulers.io())
                }
                .subscribe({ t1 ->
                    showMessage(t1)
                    addFriend.text = "Send Request"
                    addFriend.isEnabled = true
                    suggestedFriendController.updateSuggestedFriend(friend_uid!!, "No")
                }, { t2 ->
                    showMessage(t2.message)
                })
        }

        private fun showMessage(message: String?) {
            Toast.makeText(this, message, Toast.LENGTH_SHORT).show()
        }

        private fun sendRequest(friend_uid: String?) {
            var d = Single.create<String> { subscriber ->
                databaseReference
                    .child("friend_requests")
                    .child(uid)
                    .child(friend_uid)
                    .child("request_type")
                    .setValue("sent")
                    .addOnCompleteListener { task ->
                        if (task.isSuccessful) {
                            if (!subscriber.isDisposed) {
                                subscriber.onSuccess("success")
                            }
                        } else {
                            subscriber.onError(Throwable("request failed"))
                        }
                    }
            }.subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .flatMap {
                    Single.create<String> { subscriber ->
                        databaseReference
                            .child("friend_requests")
                            .child(friend_uid)
                            .child(uid)
                            .child("request_type")
                            .setValue("received")
                            .addOnCompleteListener { task ->
                                if (task.isSuccessful) {
                                    if (!subscriber.isDisposed) {
                                        subscriber.onSuccess("sent")
                                    }
                                } else {
                                    subscriber.onError(Throwable("request failed"))
                                }
                            }
                    }.subscribeOn(Schedulers.io())
                }.doOnNext {
                suggestedFriendController.updateSuggestedFriendAsync(friend_uid, "Yes")
            }.subscribe({ t1: String? ->
                realm.refresh()
                showMessage(t1)
                addFriend.text = "Delete Request"
                addFriend.isEnabled = true
            }, { t2 ->
                showMessage(t2.message)
            })
            compositeDisposable.add(d)
        }

        override fun onBackPressed() {
            super.onBackPressed()
            finish()
        }

        override fun onStop() {
            super.onStop()
            compositeDisposable.clear()
        }

        override fun onDestroy() {
            super.onDestroy()
            suggestedFriend.removeAllChangeListeners()
            realm.close()
        }
    }
}