Would this be a good pattern for a function that b...
# coroutines
n
Would this be a good pattern for a function that both fetches one single data element, and also a series of other data elements simultaneously?
Copy code
fun fetchData (scope : CoroutineScope) : Pair<Deferred<Int>, Channel<Float>> {
    // Start first operation
    val r1 : Deferred<Int> = scope.async {
        delay (200) // Pretend to do some work
        42  // Return a result
    }

    val r2 = Channel<Float> ()

    // Start second operation
    scope.launch {
        repeat (10) {
            delay (it * 100L) // Pretend to do some work
            r2.send(it.toFloat()) // Return one result
        }
        // Second operation done
        r2.close()
    }

    return Pair(r1, r2)
}


fun main () {
    val results = fetchData(GlobalScope)

    runBlocking {
        launch {
            val res1 = results.first.await()
            println("Result 1 : $res1")
        }
        launch {
            for (elem in results.second) {
                println ("Result 2 elem: $elem")
            }
        }
    }
}
Without coroutines, I'd use a callback interface with functions
onResult1(x:Int)
and
onResult2(x : Float)
and call the first one once and the second one multiple times.
w
In general, if you return a
Pair<Deferred<>, Channel<>>
then you can the await both separately. I imagine it’s not very different from having two separate functions. I’d suggest using
Flow
directly if you can instead of the channel, though
n
In my case it only makes sense to do both things at once, so having two functions wouldn't be very useful. Wouldn't Flow mean that the operation would only start when you begin to read from it? I want it to start immediately
w
Ah, that’s right, then yes. Or you could use
SharedFlow
but I’m not sure it would be better. Overall what you sent looks good to me 🙂 I’m not an expert though
n
ah I only need one consumer. Okay thanks! Then I'll do it like that