Created
May 10, 2021 20:06
-
-
Save davidmigloz/e42bc9aaf24d4c3c972660d1537429ab to your computer and use it in GitHub Desktop.
Dart vs Kotlin: asynchronous generation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'dart:async'; | |
void main() async { | |
// Stream from Iterable | |
final numList = [1, 2, 3]; | |
final numStream = Stream.fromIterable(numList); | |
await for (final num in numStream) { | |
print(num); | |
} | |
// Transforming Stream | |
getNumbersStream() | |
.where((num) => num.isEven) | |
.map((evenNum) => "Even: $evenNum") | |
.take(3) | |
.handleError((e) => print("Error: $e")) | |
.forEach((res) => print(res)); | |
// StreamController | |
final eventBus = EventBus<String>(); | |
eventBus.events.forEach(print); | |
eventBus.produceEvent("A"); | |
eventBus.produceEvent("B"); | |
} | |
Stream<int> getNumbersStream() async* { | |
var currentNumber = 0; | |
while (true) { | |
yield currentNumber++; | |
await Future.delayed(Duration(milliseconds: 200)); | |
} | |
} | |
class EventBus<T> { | |
StreamController<T> _controller = StreamController.broadcast(); | |
Stream<T> get events => _controller.stream; | |
void produceEvent(T event) { | |
_controller.add(event); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import kotlinx.coroutines.* | |
import kotlinx.coroutines.flow.* | |
fun main() = runBlocking { | |
// Stream from Iterable | |
val numList = listOf(1, 2, 3) | |
val numFlow = numList.asFlow() | |
numFlow.collect { num -> | |
println(num) | |
} | |
// Transforming Stream | |
val job1 = getNumbersStream() | |
.filter { num -> num % 2 == 0 } | |
.map { evenNum -> "Even: $evenNum" } | |
.take(3) | |
.catch { e -> println("Error: $e") } | |
.onEach { res -> println(res) } | |
.launchIn(this) | |
// SharedFlow | |
val eventBus = EventBus<String>() | |
val job2 = eventBus.events.onEach(::println).launchIn(this) | |
val job3 = launch { | |
eventBus.produceEvent("A") | |
eventBus.produceEvent("B") | |
} | |
job1.join() | |
job3.join() | |
job2.cancelAndJoin() | |
} | |
fun getNumbersStream(): Flow<Int> = flow { | |
var currentNumber = 0 | |
while (true) { | |
emit(currentNumber++) | |
delay(200) | |
} | |
} | |
class EventBus<T> { | |
private val _events = MutableSharedFlow<T>() | |
val events = _events.asSharedFlow() | |
suspend fun produceEvent(event: T) { | |
_events.emit(event) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment