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

Pablichjenkov

09/03/2019, 8:57 PM
Whats the closest equivalent to below code using
Flow
. Or in other words the
create
and
just
operator equivalents.
Copy code
Observable
		.create(
			{ emitter: Emitter<Boolean> ->
                                 // Do stuff and onNext
                        },
			Emitter.BackpressureMode.BUFFER
                  )

// Also for this 

Observable.just(true)
I am using bellow builder but wanted to see other alternatives
Copy code
flow { flowCollector -> ...// Do stuff and emit }
e

elizarov

09/03/2019, 9:02 PM
Observable.just(x)
->
flowOf(x)
Observable.create { e -> ... e.onNext(x) }
->
flow { ... emit(x) }
BackpressureMode.BUFFER
-> append
.buffer()
operator
p

Pablichjenkov

09/03/2019, 9:04 PM
Got you, thnks
p

Paul Woitaschek

09/04/2019, 9:36 AM
@elizarov Wasn't that flow builder non thread safe?
e

elizarov

09/04/2019, 9:38 AM
Indeed, it is not thread-safe. If “do stuff” is doing something across threads, then:
Observable.create({ e -> ... e.onNext(x) }, BUFFERED)
->
callbackFlow { ... offer(x) }
(
callbackFlow
is buffered by default)
p

Paul Woitaschek

09/04/2019, 9:44 AM
Maybe it should be called
nonThreadSafeFlow
instead of
flow
😉
e

elizarov

09/04/2019, 9:49 AM
This is oxymoron.
Flow
is a sequential, not a thread-safe primitive by design.
For thread-safety and communication between coroutines we have a
Channel
To make this difference absolutely explicit we even have different method names.
Flow
->
emit
,
Channel
-> `send`/`offer`.
👍 1
p

Paul Woitaschek

09/04/2019, 10:06 AM
What does this thread safety mean in the context of coroutines?
emit
says
This method is not thread-safe and should not be invoked concurrently.
This is correct:
flow<Int> { emitAll(flowOf(1, 2, 3)) }
And this isnt?
Copy code
flow<Int> {
        coroutineScope {
          launch { emitAll(flowOf(1, 2, 3)) }
          launch { emitAll(flowOf(1, 2, 3)) }
        }
g

gildor

09/04/2019, 10:25 AM
Yes, second is incorrect
p

Pablichjenkov

09/04/2019, 11:15 PM
Good point @Paul Woitaschek. Then calling
flow.emitt()
from multiple threads does not garantee the events get pipelined? Is that correct? Unless the flow is backed up by a channel?
👌 1
3 Views