https://kotlinlang.org logo
#coroutines
Title
# coroutines
g

gsala

11/09/2020, 12:00 PM
Is it a bad idea to pass a
CoroutineScope
to a function, instead of making the function suspendable and then call
coroutineScope {}
inside? What I'm going for:
Copy code
fun connect(
            device: BluetoothDevice,
            connectionScope: CoroutineScope,
    ): StateFlow<BleConnectionState>
I want to have the consumers of this API decide what the lifetime/scope of the BLE connection should be
m

marstran

11/09/2020, 12:19 PM
Letting the caller decide the scope is a normal convention. The way many people do it is to take the scope as an receiver parameter:
Copy code
fun CoroutineScope.connect(device: BluetoothDevice): StateFlow<BleConnectionState>
g

gsala

11/09/2020, 4:35 PM
This helped me understand a couple of things. But what about if the function is a member function of a class with some state I need to mutate? If I declare it as an extension function, it can't be called publicly. Would it be then good practice to have it as a function parameter?
w

wasyl

11/09/2020, 8:15 PM
> If I declare it as an extension function, it can’t be called publicly. Just fyi, you can, although it’s not very convenient
👍 1
7 Views