How to clear this error Realm Kotlin android! [RLM_ERR_WRONG_TRANSACTION_STATE]: Trying to modify database while in read transaction

type here

import android.util.Log
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import io.realm.kotlin.UpdatePolicy
import io.realm.kotlin.delete
import io.realm.kotlin.ext.query
import io.realm.kotlin.ext.toRealmSet
import io.realm.kotlin.query.RealmResults
import kotlinx.coroutines.launch

class MainViewModel : ViewModel() {
    private val realm = RealmApplication.realm
    private val _usersLiveData = MutableLiveData<List<User>>()
    val usersLiveData: LiveData<List<User>> = _usersLiveData
    private val _currentUser = MutableLiveData<User>()
    val currentUser : LiveData<User> = _currentUser
    fun addUser(
        email : String ,
        username : String ,
        password : String ,
        otp : String
    ) {
        viewModelScope.launch {
            realm.write {
                val user = User().apply {
                    this.username = username
                    this.email = email
                    this.password = password
                }
                copyToRealm(user , updatePolicy = UpdatePolicy.ALL)
                val generateOtp = Otp().apply {
                    this.code = otp
                    this.id = user.email.toString()
                }
                copyToRealm(generateOtp , updatePolicy = UpdatePolicy.ALL)
            }
        }
    }

    fun verifyOtp(
        enteredOtp : String ,
        email : String ,
        callback : (success : Boolean) -> Unit
    ) {
        viewModelScope.launch {
            try {
                val otpObject = realm.query<Otp>("id == $0" , email).find().first()
                if (otpObject.code == enteredOtp) {
                    realm.write {
                        this.delete<Otp>() // Delete the used OTP
                    }
                    callback(true)
                    realm.query<User>("email == $0", email).find().first().also {
                        realm.writeBlocking {
                            findLatest(it)?.isLoggedIn = true
                        }
                    }

                } else {
                    callback(false)
                }
            } catch (exception : Exception) {
                Log.e("OtpViewModel" , "Error verifying user: ${exception.message}")
            }

        }
    }

    fun loginUser(email : String, password : String, otp : String, callback : (success : Boolean) -> Unit){
        viewModelScope.launch {
            try {
                val userObject = realm.query<User>("email == $0 AND password == $1", email, password).find().first()
                if(userObject.isLoggedIn){
                    val generateOtp = Otp().apply {
                        this.code = otp
                        this.id = email
                    }
                    realm.write {
                        copyToRealm(generateOtp , updatePolicy = UpdatePolicy.ALL)
                    }
                    realm.query<User>("email == $0", email).find().first().also {
                        realm.writeBlocking {
                            findLatest(it)?.isLoggedIn = true
                            findLatest(it)?.currentUser = true
                        }
                    }
                    callback(true)
                }else{
                    callback(false)
                }
            }catch (exception : Exception){
                callback(false)
                Log.e("LoginViewModel" , "User Login Failed: ${exception.message}")
            }
        }
    }
    fun checkUserAlreadyExists(email: String, username: String, callback : (success : Boolean) -> Unit){
        viewModelScope.launch {
            try {
                realm.query<User>("email == $0 OR username == $1", email, username).find().first()
                callback(true)
            }catch (exception : Exception){
                callback(false)
                Log.e("SignupViewModel" , "User not exists: ${exception.message}")
            }
        }
    }

    fun setCurrentUser(selectedUser: User) {
        viewModelScope.launch {
            try {
                realm.query<User>("email == $0", selectedUser.email).find().first().also {
                    realm.writeBlocking {
                        findLatest(it)?.currentUser = true
                    }
                    Log.e("SignupViewModel" , "User updated: Done")
                }
                realm.query<User>("email != $0",selectedUser.email).find().also {
                    realm.writeBlocking{
                        this.apply {
                            it.forEach {
                                it.currentUser = false
                            }
                        }
                    }
                    Log.e("SignupViewModel2" , "User updated: Done")
                }
            }catch (exception : Exception){
                Log.e("SignupViewModel" , "User not exists: ${exception.message}")
            }
            
        }
    }
    fun getAllUsers() {
        viewModelScope.launch {
            val userResults: RealmResults<User> = realm.query<User>().find()
            val users = userResults.toList()
            _usersLiveData.postValue(users)
        }
    }
    fun currentUser(){
        viewModelScope.launch {
            try {
                val currentUserResult = realm.query<User>("currentUser==$0", true).find().first()
                _currentUser.postValue(currentUserResult)
                val list = currentUserResult.username
                Log.e("HomeViewModel" , "Current User is: $list")
            }catch (exception : Exception){
                Log.e("HomeViewModel" , "User not found: ${exception.message}")
            }

        }

    }

}`

Error occurs in setCurrentUser Method…other users is not getting updated

The selected user must become true and other users parameters must be false.But keep on getting this error.I tried all the mentioned details in documentations but nothing seems to work. Please if anyone can solve this it would be of great help

[RLM_ERR_WRONG_TRANSACTION_STATE]: Trying to modify database while in read transaction

New contributor

Arunika is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật