alexa
Facebook
Twitter
LinkedIn
Instagram
Whatsapp
Call Now
Quick Inquiry

How to create a list from scanned BLE results in android ?

How to create a list from scanned BLE results in android ?

You could use the liveData builder to collect the Flow's values into a MutableList.

Here I copy the MutableList using toList() before emitting it since RecyclerView Adapters don't play well with mutable data sources.

 val scanResults: LiveData<List<BleScanResult>> = liveData {
    val cumulativeResults = mutableListOf<BleScanResult>()

    scanEnabled.flatMapLatest { doScan ->
        if (doScan) {
            repository.bluetoothScan().map { BleScanResult(it.device.name, it.device.address) }
        } else {
            emptyFlow()
        }
    }.collect {
        cumulativeResults += it
        emit(cumulativeResults.toList())
    }
} 

If you want to avoid duplicate entries and reordering of entries, you can use a set like this:

 val scanResults: LiveData<List<BleScanResult>> = liveData {
    val cumulativeResults = mutableSetOf<BleScanResult>()

    scanEnabled.flatMapLatest { doScan ->
        if (doScan) {
            repository.bluetoothScan().map { BleScanResult(it.device.name, it.device.address) }
        } else {
            emptyFlow()
        }
    }.collect {
        if (it !in cumulativeResults) {
            cumulativeResults += it
            emit(cumulativeResults.toList())
        }
    }
}

156 0
7

Write a Comments


* Be the first to Make Comment

GoodFirms Badge
GoodFirms Badge

Fix Your Meeting With Our SEO Consultants in India To Grow Your Business Online