Omkar Amberkar
07/16/2021, 3:15 PMsharedflow
which would be eventually replaced by network call polling every few seconds. This is what I am got so far but still not what I expect, my expectation
1. Start polling once at least one terminal operator is present collect
2. Stop polling when no terminal operator
3. Share same value across all the terminal operator collect
, but as you can see, the values are different.
Also to add, when I cancel
a pollingScope
, the send
function is still called since the flow is active and keeps throwing exception
due to job cancellation.
Help much appreciated!!!
@ExperimentalCoroutinesApi
fun poll(scope: CoroutineScope) = callbackFlow {
invokeOnClose { Timber.e("Debug: channel closed") }
while (true) {
try {
val nextInt = Random.nextInt(0, 100)
Timber.e("Debug: nextInt -> $nextInt")
send(nextInt)
delay(MIN_REFRESH_TIME_MS)
} catch (throwable: Throwable) {
Timber.e("Debug: error -> ${throwable.message}")
}
}
}.shareIn(scope = scope, replay = 1, started = SharingStarted.WhileSubscribed())
pollingScope.launch {
engine.poll(applicationScope).collect {
Timber.e("Debug: collect 1 -> $it")
}
}
pollingScope.launch {
engine.poll(applicationScope).collect {
Timber.e("Debug: collect 2 -> $it")
}
}
pollingScope.launch {
engine.poll(randomScope).collect {
Timber.e("Debug: collect 3 -> $it")
}
}
$poll: Debug: nextInt -> 59
$poll: Debug: nextInt -> 68
$poll: Debug: nextInt -> 73
$poll$3$invokeSuspend$$inlined$collect: Debug: collect 2 -> 73
$poll$2$invokeSuspend$$inlined$collect: Debug: collect 1 -> 59
$poll$4$invokeSuspend$$inlined$collect: Debug: collect 3 -> 68
Sourabh Rawat
07/16/2021, 3:27 PMDominaezzz
07/16/2021, 4:59 PMshareIn
.Dominaezzz
07/16/2021, 4:59 PMOmkar Amberkar
07/16/2021, 5:01 PMDominaezzz
07/16/2021, 5:03 PMval flow = engine.poll(applicationScope)
pollingScope.launch {
flow.collect {
Timber.e("Debug: collect 1 -> $it")
}
}
pollingScope.launch {
flow.collect {
Timber.e("Debug: collect 2 -> $it")
}
}
pollingScope.launch {
flow.collect {
Timber.e("Debug: collect 3 -> $it")
}
}
Omkar Amberkar
07/16/2021, 5:06 PMcollect
operators can be in different parts of the application, so I suppose I need to convert the poll function to a property and share that property from a functionOmkar Amberkar
07/16/2021, 5:07 PMOmkar Amberkar
07/17/2021, 12:01 AMcollect
without affecting others? I see if I cancel one of the scopes, there is an error thrown by the send
functionDominaezzz
07/17/2021, 12:52 AMOmkar Amberkar
07/17/2021, 2:32 PMsend
throwing error of job cancelDominaezzz
07/17/2021, 3:43 PMDominaezzz
07/17/2021, 3:44 PMOmkar Amberkar
07/17/2021, 5:09 PMDominaezzz
07/17/2021, 5:20 PM