Rx Kotlin: map function cannot infer return type
In an application that connects to bluetooth devices, I use the following function using RxKotlin:
private fun startBluetoothPair(device: BluetoothDevice) {
Observable.just(device)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.map {
var uuid: UUID = BLUETOOTH_UUID
var socket = it.createRfcommSocketToServiceRecord(uuid)
socket.connect()
return socket
}
.subscribe {
// Do something with the BluetoothSocket
}
}
This function should just connect to the bluetoothdevice in the background and then do something to the socket (again in the mainthread). However , cant map
handle the part return socket
telling me it exists Type mismatch
, it found BluetoothSocket
where it needed it Unit
.
What's going on here? I thought the map should be able to infer the return type.
source to share
In your map function, replace the operator
return socket
from
return@map socket
Because the return statement is usually used to return values ββfor top level functions. For lambda expressions and inline (nested) functions, use return on labels, that is, return @ {username} . You can also leave the last line up to in this case and the compiler will process it for you, treating the last line as the return value for the inline function. But for better readability, I definitely prefer the qualified return syntax. You can read more details in the kotlin documentation here and here socket
source to share