v0ldem0rt
05/08/2020, 5:05 PMVsevolod Tolstopyatov [JB]
05/08/2020, 6:03 PMStateFlow
for reactive state handling is here!
• Most of the existing Flow
operators have left their experimental status
• runInterruptible
primitive for tying cancellation and interruptions
• Integration module for RxJava3
• Integration with BlockHound to detect inappropriate blocking calls
Thanks to all contributors!
Full changelog: https://github.com/Kotlin/kotlinx.coroutines/releases/tag/1.3.6SrSouza
05/10/2020, 1:03 AMconsumeAsFlow
and receiveAsFlow
, and what the different use cases of both?dave08
05/10/2020, 7:20 AMdelay(1000L)
helps... not sure what the problems was though... 🤔.Mouaad
05/10/2020, 2:56 PMMutableStateFlow
interface documentation says:
A mutable [StateFlow] that provides a setter for [value] and a method to [close] the flow.
However, I can’t see any close
method! I am missing something ?ec
05/10/2020, 4:15 PMfun main() = runBlocking {
val fl1 = flow {
for (i in 1..3)
emit(i)
}
val time = measureTimeMillis {
fl1.map { slowComp(it) }.buffer().collect { println(it) }
}
println("TIME: $time")
}
suspend fun slowComp(i: Int): Int {
delay(1000)
return i * i
}
Orhan Tozan
05/10/2020, 5:16 PMStateFlow
to another StateFlow
? stateFlow.map { } as StateFlow<T>
throws a ClassCastExceptionstreetsofboston
05/10/2020, 5:19 PMHasan
05/10/2020, 9:13 PMfun asyncOp(nums: List<Int>, mult: Int, id: String) = GlobalScope.async {
println("1 - $id: $mult times list computing asynchronously")
Thread.sleep(2000L * mult)
println("2 - $id: $mult times list computing asynchronously")
Thread.sleep(1000L * mult)
nums.map { it * mult }
}
suspend fun main() {
val nums = listOf(1,2,3,4,5,6)
val double = asyncOp(nums, 2,"first")
val triple = asyncOp(nums, 3,"second")
println("Double requested: $double")
println("Triple requested: $triple")
println("Waiting...")
println(awaitAll(triple, double))
}
This works as intended, but Intellij suggested this instead:
suspend fun asyncOp(nums: List<Int>, mult: Int, id: String) =
withContext(Dispatchers.Default) {
println("1 - $id: $mult times list computing asynchronously")
Thread.sleep(2000L * mult)
println("2 - $id: $mult times list computing asynchronously")
Thread.sleep(1000L * mult)
nums.map { it * mult }
}
But this runs it in a blocking way which is not what I wanted.
What do you guys think? Where might I be going wrong?gpeal
05/11/2020, 2:47 AMSinan Kozak
05/11/2020, 10:43 AMMore than one file was found with OS independent path 'win32-x86-64/attach_hotspot_windows.dll'
asad.awadia
05/11/2020, 1:39 PMchristophsturm
05/11/2020, 7:09 PMSrSouza
05/12/2020, 12:49 AMBroadcastChannel.openSubscriber().consumeAsFlow()
and I use at the flow launchIn(Scope)
that's return a Job, but I think that when a cancel this job, the Channel is not being canceled, when I use something like Flow.first
, the channel is cancelled. How can I cancel a Flow that canceling it will cancel the Channel too?haroldadmin
05/12/2020, 7:05 AMclass JobProcessor(val coroutineContext: CoroutineContext): CoroutineScope {
val queue1 = Channel<Job>(Channel.UNLIMITED)
val queue2 = Channel<Job>(Channel.UNLIMITED)
init {
while (isActive) {
selectJob()
}
}
private suspend fun selectJob() {
select {
queue1.onReceive { job -> process(job) }
queue2.onReceive { job -> launch { process(job) } }
}
}
fun sendJobToQueue1() { ... }
fun sendJobToQueue2() { ... }
}
Jobs in Queue 1 are processed immediately, but jobs in Queue 2 are processed in a separate coroutine because I don't want the select
statement to wait for it to complete. Jobs in Queue 1 are more important, so the biased nature of select
works in favour of this design.
In a benchmarking environment, I want to send a lot of jobs to both queues of this processor and then wait until all of them are complete to find how much time it took to process them. I am accomplishing it this way:
while (isActive && (!queue1.isEmpty || !queue2.isEmpty)) {
selectJob()
}
This waits until both queues have been drained. The problem is that jobs of queue2 are processed in different coroutines, so even if the queue is drained it does not mean that all its jobs have finished processing.
Is there a way for me to wait until jobs of queue2 have finished processing?Dmitry Khasanov
05/12/2020, 5:57 PMsuspend fun loadData(id: Long) = flow {
fetchData(id) <-- now this is blocking function, how can I launch it in non blocking mode?
roomDao.select(id)
.collect {
emit(result)
}
}.flowOn(<http://Dispatchers.IO|Dispatchers.IO>)
suspend fun fetchData(id) {
// make http request here and put data into database
}
Hi all. How can I launch fetchData
function in parallel from flow {}
?Seri
05/12/2020, 8:01 PMMutex.withLock { ... }
, but with calls while the Mutex is locked being discarded instead of suspending.Stephan Schroeder
05/12/2020, 8:30 PMTo run the coroutine only on the main UI thread, we should specify Dispatchers.Main as an argument:
launch(Dispatchers.Main) {
updateResults()
}
I would have expected Dispatchers.Swing
to be used here, it is available in the course's setup.
So a) under which circumstances is Dispatchers.Main
equal to Dispatchers.Swing
and
b) If I want to use a Dispatcher backed by a single Thread (to avoid concurrent access on some unsychronized code), if I'm in a situation where Dispatchers.Main
is equal to Dispatchers.Swing
, and I don't want to use the UI-Thread to be responsible, which Dispatcher do I use instead? (AFAIK Dispatchers.Default
is backed by as many threads as the computer has Hyperthreads and <http://Dispatchers.IO|Dispatchers.IO>
is very specific as well.) Is there something better than Executors.newSingleThreadExecutor().asCoroutineDispatcher()
?
c) assuming I'm not on the JVM (and using Executors
is therefore not an option), what's the Kotlin Multiplatform solution to create your own CoroutineDispatcher
with a specific thread-count?voben
05/13/2020, 3:19 AMdoSomethingElse()
get called before the network call completes? How could I improve this?
suspend fun signOut() {
coroutineScope {
launch {
makeNetworkRequest() // suspending function
}
}
doSomethingElse()
}
gregd
05/13/2020, 2:47 PMCoroutineScope
.
I have a pretty standard Android architecture: ViewModel, Repository, DataSource & API layers.
I want to pass ViewModel.viewModelScope
from the ViewModel to the API layer, BUT I don’t need it in the intermediate layers (Repo & DS). What do I do?
First thing that comes to my mind is marking all in-between functions with suspend
, which would pass the Scope implicitly.
But according to @elizarov we should only mark the function with suspend
if it’s really going to suspend, and those intermediate layers definitely won’t.
So, is there a better way? Is there a proper way? How do you do it?David Glasser
05/13/2020, 7:45 PMwithSomething
that either can be passed a non-suspend block and can be called from either a suspend or non-suspend block and basically does some sort of try { block() } finally { … }
, and a suspend inline function withSomethingSuspend
that can be passed a suspend block and does a more complex withContext
-based trick to manage the same thing. right now you have to choose to use the correct function name for your context; we made the first function non-inline so that you can’t accidentally call it with a suspend block. is there any way we could have just one function name? or at least declare that the first one’s block can’t be suspend so that we could make it inline?Mauricio Barbosa
05/13/2020, 8:36 PMclass UserApiClient(private val rxJavaBasedApi) {
suspend fun getUser(): User = withContext(<http://Dispatchers.IO|Dispatchers.IO>) {
rxJavaBasedApi.getUser().blockingGet()
}
}
Or there's a better approach?Krzysztof
05/13/2020, 9:28 PMclass org.test.reactive.kitchen.SuspendedKitchen {
suspend fun getPotatoes(): Potatoes = ...
fun chop(potatoes: Potatoes): ChoppedPotatoes = ...
fun fry(fish: Fish): FriedFish = ...
suspend fun fry(choppedPotatoes: ChoppedPotatoes): Chips = ...
}
Now if I have code like that:
launch {
val kitchen = SuspendedKitchen()
val chips = kitchen.getPotatoes()
.let(kitchen::chop)
.let(kitchen::fry) // <-- does not work
}
The .let(kitchen:fry)
fails with:
Callable reference resolution ambiguity:
public final suspend fun fry(choppedPotatoes: ChoppedPotatoes): Chips defined in org.test.reactive.kitchen.SuspendedKitchen public final fun fry(fish: Fish): FriedFish defined in org.test.reactive.kitchen.SuspendedKitchen
It complains about totally different types so I don't know how is that ambiguous. Does suspend mess up type resolution?
But in such case why this one works fine:
launch {
val kitchen = SuspendedKitchen()
val chips = kitchen.getPotatoes()
.let(kitchen::chop)
.let { kitchen.fry(it) } // <-- works
}
Is that expected behavior? I don't see why they would behave differently?tmg
05/14/2020, 10:23 AMclass Foo {
suspending fun foo() { /* some code */ }
And inside it I would like to launch some child coroutines (and await their ending, so, like coroutineScope {}
), what’s the correct pattern for it?
I’ve seen people using class Foo : CoroutineScope
to be able use use launch or coroutineScope directly, but what does this actually do?bbaldino
05/14/2020, 3:43 PM/user/{userId}
, how can I make sure requests pertaining to a specific userId
are handled serially, but requests for different `userId`s can be handled in parallel? I don't want to use a single-threaded dispatcher per userId
, I'd like to have a single shared pool that handles all the requests, just enforcing that requests for a given userId
are handled in order. (I think this is more of a general coroutine question with ktor as an example than a ktor-specific question, but let me know if I'm wrong)kevin.cianfarini
05/14/2020, 6:57 PMjames
05/14/2020, 7:34 PMsuspend fun doSomething() = withContext(coroutineContext) {
launch {
while(isActive) {
println("I'm Still Here")
delay(1000)
}
}
}
If that suspend function get’s cancelled due to an OOM exception how do I insure that the job that was launch is also cancelled?myanmarking
05/15/2020, 5:14 PMprivate val repository = DataRepository()
private val viewModelJob = SupervisorJob()
private val viewModelScope = CoroutineScope(Main+viewModelJob)
val mNowPlayingDataLiveData = MutableLiveData<NowPlayingMovies>()
fun DataFromrepository(page :Int){
viewModelScope.launch {
val response = repository.getDataFromServer(page)
if(response.isSuccessful){
mNowPlayingDataLiveData .value = response.body()
}}
Ali Sabzevari
05/15/2020, 11:30 PMCOUNTER=0
while :
do
COUNTER=$((COUNTER + 1))
echo "$COUNTER"
sleep 1
done
And a kotlin code that runs this script in a process:
fun InputStream.linesToFlow() = channelFlow<String> {
reader().forEachLine {
offer(it)
}
}
fun main() {
runBlocking {
val p = ProcessBuilder("./cmd.sh").start()
p.inputStream.linesToFlow().map {
println(it)
it
}.filter { "3" in it }.first()
println("Done")
p.waitFor()
}
}
I expect this script to have this output:
1
2
3
Done
But it doesn't print anything!mayojava
05/17/2020, 1:58 PMkotlinx.coroutines
library but this task is constantly failing Task :kotlinx-coroutines-jdk9:compileKotlin FAILED
. I will appreciate any pointers to solving thismayojava
05/17/2020, 1:58 PMkotlinx.coroutines
library but this task is constantly failing Task :kotlinx-coroutines-jdk9:compileKotlin FAILED
. I will appreciate any pointers to solving thisRachid
05/17/2020, 2:45 PMmayojava
05/18/2020, 2:09 AMe: /IdeaProjects/kotlinx.coroutines/reactive/kotlinx-coroutines-jdk9/src/Await.kt: (21, 24): Unresolved reference: Flow
e: /IdeaProjects/kotlinx.coroutines/reactive/kotlinx-coroutines-jdk9/src/Publish.kt: (37, 25): Cannot access class 'java.util.concurrent.Flow.Publisher'. Check your module classpath for missing or conflicting dependencies
araqnid
05/18/2020, 6:02 AMmayojava
05/18/2020, 8:13 AM