从 Flow

问题描述

我正在从移动设备获取联系人并在成功获取联系人后发送每个联系人,但我无法在发送新联系人时更新 UI。但是如果我在发出一个值后使用延迟函数,它就可以正常工作。

    suspend fun getAllContactsFromAndroidContacts(): Flow<ContactsResponse<Contact>> =
            withContext(dispatchers.IO) {
                flow {
                    val currentTime = System.currentTimeMillis()
                    val id = ContactsContract.Contacts._ID
                    val displayName = ContactsContract.Contacts.disPLAY_NAME_PRIMARY
                    val mCursor = context.contentResolver?.query(
                        ContactsContract.Contacts.CONTENT_URI,null,displayName
                    )
    
                    mCursor?.use { cursor ->
                        if (cursor.count > 0) {
                            val total = cursor.count
                            try {
                                while (cursor.movetoNext()) {
                                    val contactId = cursor.getString(cursor.getColumnIndex(id))
                                    val name = cursor.getString(cursor.getColumnIndex(displayName))
                                    val contact = Contact(
                                        contactId = contactId.toInt(),name = name,phoneNumbers = getPhoneNumbers(contactId),emails = getEmails(contactId),addresses = getAdresses(contactId),organization = getorganization(contactId).company,events = getEvents(contactId),photo = getPhoto(contactId.toLong()),account = getAccountNameByContactById(contactId),lastUpdate = currentTime
                                    )
                                    val position = cursor.position
    
                                    val progress = (position.toFloat().div(total.toFloat())).times(100)
                                    **emit(ContactsResponse.OnProgressUpdate(round(progress),contact))**
    //                                delay(100)
                                }
                            } catch (e: Exception) {
                                emit(ContactsResponse.Failure(e))
                            }
                        } else {
                            emit(ContactsResponse.NoDataFound)
                        }
                    }
                    if (mCursor == null)
                        emit(ContactsResponse.NoDataFound)
                }
            }

在我的片段中,我正在收集这样的值:

lifecycleScope.launchWhenStarted {
            contactsviewmodel.contactsResponse.collect { response ->
                when (response) {
                    is ContactsResponse.OnProgressUpdate -> {
                        updateProgress(response.progress,response.value)
                    }
                    else -> Unit
                }
            }
        }

有了这个,用户界面没有任何变化。 但是如果我使用该延迟()函数,一切正常 谢谢

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)