Kotlin Coroutines Flow is coming to provide a cold asynchronous data stream that emits values sequentially within a coroutine. Flow allows mapping, filtering, and collecting values, handles exceptions transparently, and preserves context. It can integrate with existing APIs like Room and Retrofit using adapters, and is the primary way to handle async streams going forward. Channels will still be used for hot streams and synchronization between coroutines.
Utilizing Kotlin Flows in an Android application
Vijay will be revealing to you the kind of challenges we face while working with asynchronous data streams and how Kotlin Flows solves them.
Learn the latest tips, tricks, and tools for Android Development from our international team of Android Developers in Bangkok!
Utilizing Kotlin Flows in an Android application
Vijay will be revealing to you the kind of challenges we face while working with asynchronous data streams and how Kotlin Flows solves them.
Learn the latest tips, tricks, and tools for Android Development from our international team of Android Developers in Bangkok!
Blazing Fast, Pure Effects without Monads — LambdaConf 2018John De Goes
Effect monads like IO are the way functional programmers interact with the real world. Yet, monadic effects in programming languages like Scala often perform poorly compared to their Haskell counterparts—as much as 10x slower in some benchmarks. In this presentation, John A. De Goes, author of the Scalaz 8 effect system, dredges up an old paper to cast new light on the question of how to model effects, and comes to the surprising conclusion that in Scala, monads may not be the fastest way to model purely functional effects. Join John as he shows a new model of effects that offers performance improvements without sacrificing the wonderful purity that functional programmers rely on to reason about their software.
Threading Made Easy! A Busy Developer’s Guide to Kotlin CoroutinesLauren Yew
Kotlin Coroutines is a powerful threading library for Kotlin, released by JetBrains in 2018. At The New York Times, we recently migrated our core libraries and parts of our News app from RxJava to Kotlin Coroutines. In this talk we’ll share lessons learned and best practices to understand, migrate to, and use Kotlin Coroutines & Flows.
In this presentation, you will learn:
What Coroutines are and how they function
How to use Kotlin Coroutines & Flows (with real world examples and demos)
Where and why you should use Coroutines & Flows in your app
How to avoid the pitfalls of Coroutines
Kotlin Coroutines vs. RxJava
Lessons learned from migrating to Kotlin Coroutines from RxJava in large legacy projects & libraries
By the end of this talk, you will be able to apply Kotlin Coroutines to your own app, run the provided sample code yourself, and convince your team to give Kotlin Coroutines a try!
This is an introduction to Kotlin Coroutines and How we can use it in Android. I have tried cover all the basic stuff of coroutine and also added a comparison of thread and coroutine. Github sample project link: https://github.com/bipinvaylu/kotlin-coroutines
Slides with speaker contents: https://docs.google.com/presentation/d/1Wn9ImL9meON2Ohg7pPVYCXKNezilJyX6ewDWU3ljrwE/edit?usp=sharing
Gor Nishanov, C++ Coroutines – a negative overhead abstractionSergey Platonov
C++ coroutines are one of the few major features that may land in C++17. We will look at the current standardization status, available experimental implementations and develop a small coroutine adapter over raw C networking APIs that will beat hand-crafted state machine in performance.
Introduces the functional programming ideas of Functor, Apply, Applicative And Monad. Shows how to implement each in Scala with Scalaz and how to validate the implementation using property based test using specs2 and scalacheck.
Modern applications are concurrent, parallel, asynchronous, and synchronous; they utilize many different subsystems, including network systems, actor systems, distributed systems, and more. Across all these modes of computation and different subsystems, the one constant is failure. Errors happen everywhere, and taming their monstrous complexity in a way that helps developers write correct code and troubleshoot failures is one of the hardest challenges of modern application development.
In this presentation, created just for the Dublin Scala Meetup, John A. De Goes and Kai from 7mind.io will take attendees on a tour of error management in Scala, comparing and contrasting Scala's own Future type, and the ZIO effect type. You'll see how functional effects provide features that go way beyond Future: including unified errors across all modes of computation, powerful error operators, lossless error propagation, compiler-assisted error handling, and a stunning new feature for debugging, sponsored by Irish consultancy 7mind.io, will be unveiled exclusively at this presentation.
Come learn about how modern functional effect systems like ZIO provide compelling new solutions to the problems of everyday error management.
Some parts of our applications don't need to be asynchronous or interact with the outside world: it's enough that they are stateful, possibly with the ability to handle failure, context, and logging. Although you can use ZIO 2 or monad transformers for this task, both come with drawbacks. In this presentation, Jorge Vásquez will introduce you to ZPure, a data type from ZIO Prelude, which lets you scale back on the power of ZIO 2, but with the same high-performance, type-inference, and ergonomics you expect from ZIO 2 libraries.
I used these slides to present the benefits of using Kotlin to a group of people I work with. The presentation focuses on comparing Kotlin to Java, and in particular showing how Kotlin can help in writing safer, more concise and readable code. I used a few java gotchas/puzzles to demonstrate how Kotlin may prevent us from doing silly things.
Jetpack Compose - Android’s modern toolkit for building native UIGilang Ramadhan
Jetpack Compose simplifies and accelerates UI development on Android. Quickly bring your app to life with less code, powerful tools, and intuitive Kotlin APIs.
Slides from my talk at UA Mobile 2017, 2017-11-25
Video: https://www.youtube.com/watch?v=tql9fmWX_oc
Modern programming cannot be imagined without long-running operations such as CPU-intensive computations or blocking IO running in the background. Unfortunately, having too many active threads is very expensive and kills performance, but there's a solution - coroutines. They provide a way to avoid blocking a thread and replace it with a cheaper and more controllable operation: suspension of a coroutine.
I'll talk about generators/yield, async/await, channels, composable/delimited continuations, and its usage; consider available APIs and make the overview of standard kotlinx.coroutines library.
Kotlin Coroutines and Android sitting in a treeKai Koenig
Since the release of Kotlin 1.1 there is now the new language feature of Kotlin Coroutines available for use in Java and Android projects. Coroutines are a new way to write asynchronous and non-blocking code. They can be thought of as light-weight threads without having to deal with all the problems that threads bring to the table.
A lot of developers think that Kotlin Coroutines are mainly or only useful for Kotlin on the JVM, but that’s not true. There are a variety of use cases in which the application of Coroutines can make a lot of sense on Android.
This talk is introducing the ideas behind Kotlin Coroutines, showing how to use them in Kotlin code for both the JVM and Android via the kotlinx-coroutines APIs and then exploring specific applications in Android. Part of this is a deeper look into the use of Coroutines in higher-level frameworks such as AsyncAwait and Anko.
Functional programming can be an excellent approach to designing decoupled, reusable systems with a rich domain model. In fact, the lessons from applying DDD in a functional language translate well to object-oriented programming.
Blazing Fast, Pure Effects without Monads — LambdaConf 2018John De Goes
Effect monads like IO are the way functional programmers interact with the real world. Yet, monadic effects in programming languages like Scala often perform poorly compared to their Haskell counterparts—as much as 10x slower in some benchmarks. In this presentation, John A. De Goes, author of the Scalaz 8 effect system, dredges up an old paper to cast new light on the question of how to model effects, and comes to the surprising conclusion that in Scala, monads may not be the fastest way to model purely functional effects. Join John as he shows a new model of effects that offers performance improvements without sacrificing the wonderful purity that functional programmers rely on to reason about their software.
Threading Made Easy! A Busy Developer’s Guide to Kotlin CoroutinesLauren Yew
Kotlin Coroutines is a powerful threading library for Kotlin, released by JetBrains in 2018. At The New York Times, we recently migrated our core libraries and parts of our News app from RxJava to Kotlin Coroutines. In this talk we’ll share lessons learned and best practices to understand, migrate to, and use Kotlin Coroutines & Flows.
In this presentation, you will learn:
What Coroutines are and how they function
How to use Kotlin Coroutines & Flows (with real world examples and demos)
Where and why you should use Coroutines & Flows in your app
How to avoid the pitfalls of Coroutines
Kotlin Coroutines vs. RxJava
Lessons learned from migrating to Kotlin Coroutines from RxJava in large legacy projects & libraries
By the end of this talk, you will be able to apply Kotlin Coroutines to your own app, run the provided sample code yourself, and convince your team to give Kotlin Coroutines a try!
This is an introduction to Kotlin Coroutines and How we can use it in Android. I have tried cover all the basic stuff of coroutine and also added a comparison of thread and coroutine. Github sample project link: https://github.com/bipinvaylu/kotlin-coroutines
Slides with speaker contents: https://docs.google.com/presentation/d/1Wn9ImL9meON2Ohg7pPVYCXKNezilJyX6ewDWU3ljrwE/edit?usp=sharing
Gor Nishanov, C++ Coroutines – a negative overhead abstractionSergey Platonov
C++ coroutines are one of the few major features that may land in C++17. We will look at the current standardization status, available experimental implementations and develop a small coroutine adapter over raw C networking APIs that will beat hand-crafted state machine in performance.
Introduces the functional programming ideas of Functor, Apply, Applicative And Monad. Shows how to implement each in Scala with Scalaz and how to validate the implementation using property based test using specs2 and scalacheck.
Modern applications are concurrent, parallel, asynchronous, and synchronous; they utilize many different subsystems, including network systems, actor systems, distributed systems, and more. Across all these modes of computation and different subsystems, the one constant is failure. Errors happen everywhere, and taming their monstrous complexity in a way that helps developers write correct code and troubleshoot failures is one of the hardest challenges of modern application development.
In this presentation, created just for the Dublin Scala Meetup, John A. De Goes and Kai from 7mind.io will take attendees on a tour of error management in Scala, comparing and contrasting Scala's own Future type, and the ZIO effect type. You'll see how functional effects provide features that go way beyond Future: including unified errors across all modes of computation, powerful error operators, lossless error propagation, compiler-assisted error handling, and a stunning new feature for debugging, sponsored by Irish consultancy 7mind.io, will be unveiled exclusively at this presentation.
Come learn about how modern functional effect systems like ZIO provide compelling new solutions to the problems of everyday error management.
Some parts of our applications don't need to be asynchronous or interact with the outside world: it's enough that they are stateful, possibly with the ability to handle failure, context, and logging. Although you can use ZIO 2 or monad transformers for this task, both come with drawbacks. In this presentation, Jorge Vásquez will introduce you to ZPure, a data type from ZIO Prelude, which lets you scale back on the power of ZIO 2, but with the same high-performance, type-inference, and ergonomics you expect from ZIO 2 libraries.
I used these slides to present the benefits of using Kotlin to a group of people I work with. The presentation focuses on comparing Kotlin to Java, and in particular showing how Kotlin can help in writing safer, more concise and readable code. I used a few java gotchas/puzzles to demonstrate how Kotlin may prevent us from doing silly things.
Jetpack Compose - Android’s modern toolkit for building native UIGilang Ramadhan
Jetpack Compose simplifies and accelerates UI development on Android. Quickly bring your app to life with less code, powerful tools, and intuitive Kotlin APIs.
Slides from my talk at UA Mobile 2017, 2017-11-25
Video: https://www.youtube.com/watch?v=tql9fmWX_oc
Modern programming cannot be imagined without long-running operations such as CPU-intensive computations or blocking IO running in the background. Unfortunately, having too many active threads is very expensive and kills performance, but there's a solution - coroutines. They provide a way to avoid blocking a thread and replace it with a cheaper and more controllable operation: suspension of a coroutine.
I'll talk about generators/yield, async/await, channels, composable/delimited continuations, and its usage; consider available APIs and make the overview of standard kotlinx.coroutines library.
Kotlin Coroutines and Android sitting in a treeKai Koenig
Since the release of Kotlin 1.1 there is now the new language feature of Kotlin Coroutines available for use in Java and Android projects. Coroutines are a new way to write asynchronous and non-blocking code. They can be thought of as light-weight threads without having to deal with all the problems that threads bring to the table.
A lot of developers think that Kotlin Coroutines are mainly or only useful for Kotlin on the JVM, but that’s not true. There are a variety of use cases in which the application of Coroutines can make a lot of sense on Android.
This talk is introducing the ideas behind Kotlin Coroutines, showing how to use them in Kotlin code for both the JVM and Android via the kotlinx-coroutines APIs and then exploring specific applications in Android. Part of this is a deeper look into the use of Coroutines in higher-level frameworks such as AsyncAwait and Anko.
Functional programming can be an excellent approach to designing decoupled, reusable systems with a rich domain model. In fact, the lessons from applying DDD in a functional language translate well to object-oriented programming.
Coroutine Flows are the new hot tech in reactive apps.
They are very powerful and easy to use at the same time. the best part is they support KMP so we can share our flows with other platforms.
In this talk, I go through different flow operators and flow types (ex: SharedFlow, StateFlow, and …).
I explain their usage and compare their subtle differences.
I also cover how we can leverage Coroutines Flow and its operators to build reactive architectures.
No talk should be ended without talking about testing.
In this talk, I’ll explain how we can write readable and concise tests with Kotlin Flows that run on all platforms.
1. what is the different unbuffered and buffered channel?
2. how to implement a job queue in golang?
3. how to stop the worker in a container?
4. Shutdown with Sigterm Handling
5. Canceling Workers without Context
6. Graceful shutdown with worker
7. How to auto-scaling build agent?
8. How to cancel the current Job?
Most computers today have multiple cores and processes. That means, if you really want to fully explore the capabilities of them, you must explore concurrent programming resources. Go was developed with this in mind, offering goroutines and channels.
Although concurrent programming may seem simple with Go, there are a couple of details to keep in mind, to avoid problems. In this talk, I’m going to show a couple of practical examples with goroutines and channels, and some common pitfalls
In this talk I presented three important topics in Kotlin Standard Library: Scope Functions (let, apply, also, run and with); Annotations (Deprecated, Experimental, Jvm*, DslMarker); and Delegates (lazy, vetoable, observable)
Best practises how to reduce Android application install size & improve your app install conversation rate. Video can be found here youtu.be/ksgW-VHH-Qo
ConstraintLayout. Fell the Power of constraintsKirill Rozov
Talk about ConstraintLayout and visual Layout Editor in Android Studio 3.0.
Project that was showed on talk https://github.com/kirich1409/ConstrinatLayoutIntro.
Kotlin 1.2: Sharing code between platformsKirill Rozov
Discover what's new in Kotlin 1.2: syntax, standard library, performance and , of course, "Multiplatform project". Take closer look at how Kotlin authors see way of reusing code between platforms.
Java имеет огромное множество книг о том как правильно писать код на этом языке, какие практити стоит использовать из раза в раз для реализации стандартных паттернов программирования. За 25 лет своей истории Java накопила много проблем. Доклад проливает свет как Kotlin решает проблемы, которые есть в Java и делает программистов счастливыми снова.
Explore the innovative world of trenchless pipe repair with our comprehensive guide, "The Benefits and Techniques of Trenchless Pipe Repair." This document delves into the modern methods of repairing underground pipes without the need for extensive excavation, highlighting the numerous advantages and the latest techniques used in the industry.
Learn about the cost savings, reduced environmental impact, and minimal disruption associated with trenchless technology. Discover detailed explanations of popular techniques such as pipe bursting, cured-in-place pipe (CIPP) lining, and directional drilling. Understand how these methods can be applied to various types of infrastructure, from residential plumbing to large-scale municipal systems.
Ideal for homeowners, contractors, engineers, and anyone interested in modern plumbing solutions, this guide provides valuable insights into why trenchless pipe repair is becoming the preferred choice for pipe rehabilitation. Stay informed about the latest advancements and best practices in the field.
Courier management system project report.pdfKamal Acharya
It is now-a-days very important for the people to send or receive articles like imported furniture, electronic items, gifts, business goods and the like. People depend vastly on different transport systems which mostly use the manual way of receiving and delivering the articles. There is no way to track the articles till they are received and there is no way to let the customer know what happened in transit, once he booked some articles. In such a situation, we need a system which completely computerizes the cargo activities including time to time tracking of the articles sent. This need is fulfilled by Courier Management System software which is online software for the cargo management people that enables them to receive the goods from a source and send them to a required destination and track their status from time to time.
Overview of the fundamental roles in Hydropower generation and the components involved in wider Electrical Engineering.
This paper presents the design and construction of hydroelectric dams from the hydrologist’s survey of the valley before construction, all aspects and involved disciplines, fluid dynamics, structural engineering, generation and mains frequency regulation to the very transmission of power through the network in the United Kingdom.
Author: Robbie Edward Sayers
Collaborators and co editors: Charlie Sims and Connor Healey.
(C) 2024 Robbie E. Sayers
Immunizing Image Classifiers Against Localized Adversary Attacksgerogepatton
This paper addresses the vulnerability of deep learning models, particularly convolutional neural networks
(CNN)s, to adversarial attacks and presents a proactive training technique designed to counter them. We
introduce a novel volumization algorithm, which transforms 2D images into 3D volumetric representations.
When combined with 3D convolution and deep curriculum learning optimization (CLO), itsignificantly improves
the immunity of models against localized universal attacks by up to 40%. We evaluate our proposed approach
using contemporary CNN architectures and the modified Canadian Institute for Advanced Research (CIFAR-10
and CIFAR-100) and ImageNet Large Scale Visual Recognition Challenge (ILSVRC12) datasets, showcasing
accuracy improvements over previous techniques. The results indicate that the combination of the volumetric
input and curriculum learning holds significant promise for mitigating adversarial attacks without necessitating
adversary training.
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...Dr.Costas Sachpazis
Terzaghi's soil bearing capacity theory, developed by Karl Terzaghi, is a fundamental principle in geotechnical engineering used to determine the bearing capacity of shallow foundations. This theory provides a method to calculate the ultimate bearing capacity of soil, which is the maximum load per unit area that the soil can support without undergoing shear failure. The Calculation HTML Code included.
About
Indigenized remote control interface card suitable for MAFI system CCR equipment. Compatible for IDM8000 CCR. Backplane mounted serial and TCP/Ethernet communication module for CCR remote access. IDM 8000 CCR remote control on serial and TCP protocol.
• Remote control: Parallel or serial interface.
• Compatible with MAFI CCR system.
• Compatible with IDM8000 CCR.
• Compatible with Backplane mount serial communication.
• Compatible with commercial and Defence aviation CCR system.
• Remote control system for accessing CCR and allied system over serial or TCP.
• Indigenized local Support/presence in India.
• Easy in configuration using DIP switches.
Technical Specifications
Indigenized remote control interface card suitable for MAFI system CCR equipment. Compatible for IDM8000 CCR. Backplane mounted serial and TCP/Ethernet communication module for CCR remote access. IDM 8000 CCR remote control on serial and TCP protocol.
Key Features
Indigenized remote control interface card suitable for MAFI system CCR equipment. Compatible for IDM8000 CCR. Backplane mounted serial and TCP/Ethernet communication module for CCR remote access. IDM 8000 CCR remote control on serial and TCP protocol.
• Remote control: Parallel or serial interface
• Compatible with MAFI CCR system
• Copatiable with IDM8000 CCR
• Compatible with Backplane mount serial communication.
• Compatible with commercial and Defence aviation CCR system.
• Remote control system for accessing CCR and allied system over serial or TCP.
• Indigenized local Support/presence in India.
Application
• Remote control: Parallel or serial interface.
• Compatible with MAFI CCR system.
• Compatible with IDM8000 CCR.
• Compatible with Backplane mount serial communication.
• Compatible with commercial and Defence aviation CCR system.
• Remote control system for accessing CCR and allied system over serial or TCP.
• Indigenized local Support/presence in India.
• Easy in configuration using DIP switches.
Final project report on grocery store management system..pdfKamal Acharya
In today’s fast-changing business environment, it’s extremely important to be able to respond to client needs in the most effective and timely manner. If your customers wish to see your business online and have instant access to your products or services.
Online Grocery Store is an e-commerce website, which retails various grocery products. This project allows viewing various products available enables registered users to purchase desired products instantly using Paytm, UPI payment processor (Instant Pay) and also can place order by using Cash on Delivery (Pay Later) option. This project provides an easy access to Administrators and Managers to view orders placed using Pay Later and Instant Pay options.
In order to develop an e-commerce website, a number of Technologies must be studied and understood. These include multi-tiered architecture, server and client-side scripting techniques, implementation technologies, programming language (such as PHP, HTML, CSS, JavaScript) and MySQL relational databases. This is a project with the objective to develop a basic website where a consumer is provided with a shopping cart website and also to know about the technologies used to develop such a website.
This document will discuss each of the underlying technologies to create and implement an e- commerce website.
Democratizing Fuzzing at Scale by Abhishek Aryaabh.arya
Presented at NUS: Fuzzing and Software Security Summer School 2024
This keynote talks about the democratization of fuzzing at scale, highlighting the collaboration between open source communities, academia, and industry to advance the field of fuzzing. It delves into the history of fuzzing, the development of scalable fuzzing platforms, and the empowerment of community-driven research. The talk will further discuss recent advancements leveraging AI/ML and offer insights into the future evolution of the fuzzing landscape.
Student information management system project report ii.pdfKamal Acharya
Our project explains about the student management. This project mainly explains the various actions related to student details. This project shows some ease in adding, editing and deleting the student details. It also provides a less time consuming process for viewing, adding, editing and deleting the marks of the students.
Quality defects in TMT Bars, Possible causes and Potential Solutions.PrashantGoswami42
Maintaining high-quality standards in the production of TMT bars is crucial for ensuring structural integrity in construction. Addressing common defects through careful monitoring, standardized processes, and advanced technology can significantly improve the quality of TMT bars. Continuous training and adherence to quality control measures will also play a pivotal role in minimizing these defects.
5. Async in Kotlin
// Single value
suspend fun foo(p: Params): Value =
withContext(Dispatchers.Default) { bar(p) }
// Collection of values
suspend fun foo(p: Params): List<Value> =
buildList { while (hasMore) add(nextValue) }
// Stream of values
fun foo(p: Params): Sequence<Value> =
sequence { while (hasMore) yield(nextValue) }
6. Async in Kotlin
// Single value
suspend fun foo(p: Params): Value =
withContext(Dispatchers.Default) { bar(p) }
// Collection of values
suspend fun foo(p: Params): List<Value> =
buildList { while (hasMore) add(nextValue) }
// Stream of values
fun foo(p: Params): Sequence<Value> =
sequence { while (hasMore) yield(nextValue) }
Blocking
9. Channels
fun CoroutineScope.fooProducer(p: Params)
: ReceiveChannel<Value> {
return produce { while (hasMore) send(nextValue) }
}
val values: ReceiveChannel<Value> = fooProducer(p)
if (someCondition) {
return anotherResult // Oops! Leaked channel
}
// ... do further work with values ...
10. • Works with data sources that are intrinsically hot
Data sources that exist without application’s requests for them
• incoming network connections
• event streams
• Synchronization primitives
• For transfer data between coroutines
• Synchronize access to the same data from multiply coroutines
Channels
12. Flow is a cold asynchronous data stream that
executed sequentially (in the same coroutine)
emits values and completes normally or with an
exception
kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.flow/-flow/
15. Flow
interface Flow<out T> {
suspend fun collect(collector: FlowCollector<T>)
}
interface FlowCollector<in T> {
suspend fun emit(value: T)
}
16. Builders
// From fixed set of values
val flowA = flowOf(1, 2, 3)
// From function type () -> T
val flowB = { repeat(3) { it + 1 } }.asFlow()
// Sequential call to the emit() function
val flowC = flow {
emit(1)
emit(2)
emit(3)
}
17. fun <T> Iterator<T>.asFlow(): Flow<T>
fun <T> Iterable<T>.asFlow(): Flow<T>
fun <T> emptyFlow(): Flow<T>
fun <T> Array<T>.asFlow(): Flow<T>
fun IntRange.asFlow(): Flow<Int>
fun <T> Sequence<T>.asFlow(): Flow<T>
fun <T> (() -> T).asFlow(): Flow<T>
fun <T> flow(
block: suspend FlowCollector<T>.() -> Unit
): Flow<T>
Builders
18. • map / mapNotNull
• switchMap
• combineLatest
• debounce / sample
• delayEach / delayFlow
• Zlter / ZlterNot / ZlterIsInstance / ZlterNotNull
• zip
• catch
• onEach / onCompletion
• atMapConcat / atMapMerge
• a]enConcat / a]enMerge
Intermediate
Operators
* Full list of available operators can be found in official documentation kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.flow/-flow/
37. • Context preservation
Flow encapsulates its own execution context and never propagates or leaks it
downstream
• Exception transparency
Flow implementations never catch or handle exceptions that occur in
downstream <ows
Flow Constraints
41. interface Stream<D> {
fun subscribe(callback: Callback<D>)
fun unsubscribe(callback: Callback<D>)
}
interface Callback<D> {
fun onNext(item: D)
fun onError(error: Throwable)
fun onCompleted()
}
Old ways adapter
42. val stream = Stream<Value>()
callbackFlow<Value> { // this: ProducerScope<Value>
// ProducerScope<Value> extends SendChannel<Value>
val callback = object : Callback<Value> {
override fun onNext(item: Value) { offer(item) }
override fun onError(error: Throwable) { close(error) }
override fun onCompleted() { close() }
}
stream.subscribe(callback)
awaitClose { stream.unsubscribe(callback) }
}
Old ways adapter
48. fun <T> Observable<T>.toFlow(): Flow<T>
fun <T> Single<T>.toFlow(): Flow<T>
fun <T> Maybe<T>.toFlow(): Flow<T>
fun <T> Flowable<T>.toFlow(): Flow<T>
RxJava2 to Flow
Adapters
49. fun <T> Observable<T>.toFlow(): Flow<T>
fun <T> Single<T>.toFlow(): Flow<T>
fun <T> Maybe<T>.toFlow(): Flow<T>
fun <T> Flowable<T>.toFlow(): Flow<T>
NO FROM THE BOX :) WRITE YOU OWNRxJava2 to Flow
Adapters
51. @Dao
interface SampleDao {
}
// Request data and observe changes with RxJava
@Query("SELECT * FROM ENTITIES")
fun queryEntities(): Observable<List<Entity>>Room
// Blocking request data
@Query("SELECT * FROM ENTITIES")
fun queryEntities(): List<Entity>
52. @Dao
interface SampleDao {
}
// Request data and observe changes with RxJava
@Query("SELECT * FROM ENTITIES")
fun queryEntities(): Observable<List<Entity>>Room
// Blocking request data
@Query("SELECT * FROM ENTITIES")
fun queryEntities(): List<Entity>
// Request data using Coroutines
@Query("SELECT * FROM ENTITIES")
suspend fun queryEntities(): List<Entity>
53. @Dao
interface SampleDao {
}
// Request data and observe changes with RxJava
@Query("SELECT * FROM ENTITIES")
fun queryEntities(): Observable<List<Entity>>Room
// Blocking request data
@Query("SELECT * FROM ENTITIES")
fun queryEntities(): List<Entity>
// Request data using Coroutines
@Query("SELECT * FROM ENTITIES")
suspend fun queryEntities(): List<Entity>
// Request data and observe changes using Coroutines
@Query("SELECT * FROM ENTITIES")
fun queryEntities(): Flow<List<Entity>>
54. val database = getSampleDatabase()
GlobalScope.launch {
database.sampleDao.queryEntities().collect {
// Handle updates of entities
}
}
Room
58. fun <T> Call<T>.asFlow(): Flow<T> = callbackFlow {
enqueue(object : Callback<T> {
override fun onFailure(call: Call<T>, error: Throwable) {
close(error)
}
override fun onResponse(call: Call<T>, response: Response<T>) {
if (response.isSuccessful) {
offer(response.body()!!)
close()
} else {
close(RetrofitError(response.errorBody()))
}
}
})
awaitClose {
if (!isCanceled) {
cancel()
}
}
}
class RetrofitError(val errorBody: ResponseBody?) : Throwable()
RetroZt
59. val service = getGitHubService()
GlobalScope.launch {
service.listRepos("user-id")
.asFlow()
.collect {
// handle response
}
}
RetroZt
60. • Flow will be primary way to handle async stream
of data
• Channels will be used:
• for hot streams
• “under-the-hood” in some Flow operators
• as synchronization primitive between
Coroutines
What will be the
next?