SlideShare a Scribd company logo
1 of 32
Download to read offline
Dealing with Python Reactively
PyCon Korea 2017
Kenneth
SPEAKER
Editor
Dev team leader
Kenneth
INTRODUCTION
Ractive Progamming
RxPy
Coroutine / Generator
CH1.
CH2.
CH3.
CH1.
Reactive Programming
What is reactive programming?
CH 1. Reactive Programming
The new paradigm that focused
on the asynchronous data flow
Difficult
Key keyword #1
CH 1. Reactive Programming
Asynchronous
It can be received the data that is not guaranteed
In the asynchronous environment sequentially,
And also it can be processed the data flexible.
Key keyword #2
CH 1. Reactive Programming
Reactive
It is not executed if there is no operation (input) from the outside.
Key keyword #3
CH 1. Reactive Programming
Lightweight
Data flow can be subdivided for each purpose,
And also it can be merged again.
This makes it possible to reduce the weight.
The data flows.
CH 1. Reactive Programming
However it does not flow at the same time.
So we can not guarantee
that the data always comes.
CH 1. Reactive Programming
It can not be easy to process the data
that comes every another times.
CH 1. Reactive Programming
.next() .subscribe()
Controlling multiple data flows.
Reactive programming makes it possible.
CH 1. Reactive Programming
The data that comes from each different times concurrently,
To be sequentially
It only see the data flows.
That’s why it’s intuitive.
CH 1. Reactive Programming
Map
Filter
Merge Reduce
On Complete
On Error
Retry
Skip Buffer
CH2.
RxPy
ReactiveX (RX)
CH 2. RxPy
Microsoft announced `Volta` project in 2007
It is officially known as `Reactive Extensions` in 2009
It was gradually released as open source since 2012
def observer_generator(observer):
# It passes the string “hello” through the observer.
observer.on_next("hello")
# Likewise, it passes the string "world!" through the observer.
observer.on_next("world!")
def main():
# Create an observer, passes it to a predefined function, and receives an object that can receive it.
observable = Observable.create(observer_generator)
# Receive the observer, At this time the observer read the variable that passed at on_next.
# Oh! After the below subscribe is started, the above observer_generator will be executed.
observable.subscribe(on_next=lambda value: print(value))
hello_world.py
observable.create (Create an observer)
observer_generator
observer
def observer_generator(observer):
# It passes the string “hello” through the observer.
observer.on_next("hello")
# Likewise, it passes the string "world!" through the observer.
observer.on_next("world!")
def main():
# Create an observer, passes it to a predefined function, and receives an object that can receive it.
observable = Observable.create(observer_generator)
# Receive the observer, At this time the observer read the variable that passed at on_next.
# Oh! After the below subscribe is started, the above observer_generator will be executed.
observable.subscribe(on_next=lambda value: print(value))
hello_world.py
observable
1. next(‘hello’)
2. next(‘world!’)
observer
1. print(‘hello’)
2. print(‘world!’)
It passes the data through on_next
Print the message that received from on_next
from rx import Observable, Observer
class PrintObserver(Observer):
def on_next(self, value):
print('on_next value:%s’ % (value))
def on_completed(self):
print('on_completed !')
def on_error(self, value):
print('on_error value:%s’ % (value))
def observer_generator(observer):
observer.on_next(“break")
observer.on_next(“the ice!")
while True:
message = input()
if message:
observer.on_next(message)
else:
observer.on_completed()
break
def main():
observable = Observable.create(observer_generator)
observable.subscribe(PrintObserver())
ice_breaking.py
Observable
(Data forwarder)
Observable
(Data receiver)
subscribe()
next(‘break’)
next(‘the ice!’)
next(‘message’)
print()
print()
print()
on_next
on_next
on_next
completed()
on_completed print()
1. You can expand incoming messages by using
Predefined object in Subscribe method.
CH3.
Coroutine / Generator
Coroutine?
CH 3. Coroutine / Generator
Unlike functions,
Routines whose parents are
“equivalent” to the called function.
Python only: Coroutine can process
only the received data.
Coroutine vs General routine
CH 3. Coroutine / Generator
General
Routine
Function
call
Return
Parameters
Result
Coroutine
Function
call
Parameters
Yield
Yield
Yield
Main code Main code
Calculating
Calculating
Calculating
Send
Send
Send
Use Case
CH 3. Coroutine / Generator
Init Data
Caller Coroutine
2. Wait for the caller's input via yield
(Will be returned to caller code lines)
1. Inserting initial data to apply to coroutines
3. If you have input to the caller,
return to the coroutine code and execute the logic.
If yield appearsin the logic,
it returns to the parent code again.
(repeat)
next()
Yield
Yield
4. Finally, the caller ends the coroutine.
Close
Generator?
CH 3. Coroutine / Generator
If Coroutine is a gourmand,
The Generator is the giving tree.
A generator is a `generator`
that generates data through yield.
Do you know range function?
CH 3. Coroutine / Generator
def main():
# Use the range function to insert each value from 0 to 2
# into value and repeat it three times.
for value in range(3):
print(u’current value %d' % (value))
OUTPUT:
current_value 0
current_value 1
current_value 2
Making range function by using Generator.
CH 3. Coroutine / Generator
# It is the range function created by using the Generator.
def custom_range(number):
index = 0
while(index < number):
# At this point, we go back to the parent that called this function,
# Pass the value, and proceed to the parent's logic until we call this function again.
# This is the heart of the generator. Remember this!
yield index
index += 1
coroutine_generator.py
def main():
# Let's try to use the existing range function.
for value in range(3):
print(u'original range %d' % (value))
# Insert a line escaping for the division.
print(u'n')
# Let's try the function we just created.
for value in custom_range(3):
print(u'custom range %d' % (value))
OUTPUT
original range 0
original range 1
original range 2
custom range 0
custom range 1
custom range 2
Use Case
CH 3. Coroutine / Generator
Large Data
Memory
Process
yield
1. In a real-time cursor,
yield returns
every 500 datasets.
2. Actually there are only 500 data in memory,
so there is out of memory problem.
3. When 500 data are processed
and the process is finished,
500 data will be emptied from the memory.
Likewise, there is no out of memory problem.
4. At the end of the process,
it again gets 500 data from Large Data.
Conclusion about Generator
CH 3. Coroutine / Generator
Data that comes in real time
can be used to stabilize
the memory by using the generator!
(Performance difference is insignificant)
What is the difference
Between Coroutine and Generator?
CH 3. Coroutine / Generator
Corutine
Function
call
Parameters
Yield
Yield
Yield
Main code
Calculating
Calculating
Calculating
Send
Send
Generator
Function
call
Parameters
Yield
Yield
Yield
Main code
Calculating
Calculating
Calculating
Return
Return
Return
Send
Question
Thank you
Kennethan@nhpcw.com
http://github.com/KennethanCeyer/pycon-kr-2017
Email
GitHub

More Related Content

What's hot

Java Script Promise
Java Script PromiseJava Script Promise
Java Script Promise
Alok Guha
 
Evolution of asynchrony in (ASP).NET
Evolution of asynchrony in (ASP).NETEvolution of asynchrony in (ASP).NET
Evolution of asynchrony in (ASP).NET
Aliaksandr Famin
 
Simulation structure - Part 2
Simulation structure - Part 2Simulation structure - Part 2
Simulation structure - Part 2
guticr
 
Fixing an annoying GridView problem
Fixing an annoying GridView problemFixing an annoying GridView problem
Fixing an annoying GridView problem
Roger Pence
 

What's hot (20)

JavaScript promise
JavaScript promiseJavaScript promise
JavaScript promise
 
Lesson 5
Lesson 5Lesson 5
Lesson 5
 
Lecture 3
Lecture 3Lecture 3
Lecture 3
 
Java Script Promise
Java Script PromiseJava Script Promise
Java Script Promise
 
Callbacks and control flow in Node js
Callbacks and control flow in Node jsCallbacks and control flow in Node js
Callbacks and control flow in Node js
 
Demanding scripting
Demanding scriptingDemanding scripting
Demanding scripting
 
Difference between switch and ladder if
Difference between switch and ladder ifDifference between switch and ladder if
Difference between switch and ladder if
 
Evaluation of prefix expression with example
Evaluation of prefix expression with exampleEvaluation of prefix expression with example
Evaluation of prefix expression with example
 
Java script function
Java script functionJava script function
Java script function
 
Lect 15-16 Zaheer Abbas
Lect 15-16 Zaheer  AbbasLect 15-16 Zaheer  Abbas
Lect 15-16 Zaheer Abbas
 
Java input Scanner
Java input Scanner Java input Scanner
Java input Scanner
 
Evolution of asynchrony in (ASP).NET
Evolution of asynchrony in (ASP).NETEvolution of asynchrony in (ASP).NET
Evolution of asynchrony in (ASP).NET
 
Vp4
Vp4Vp4
Vp4
 
Java Repetiotion Statements
Java Repetiotion StatementsJava Repetiotion Statements
Java Repetiotion Statements
 
Timedobserver
TimedobserverTimedobserver
Timedobserver
 
Async History - javascript
Async History - javascriptAsync History - javascript
Async History - javascript
 
Function
FunctionFunction
Function
 
Simulation structure - Part 2
Simulation structure - Part 2Simulation structure - Part 2
Simulation structure - Part 2
 
Computer
ComputerComputer
Computer
 
Fixing an annoying GridView problem
Fixing an annoying GridView problemFixing an annoying GridView problem
Fixing an annoying GridView problem
 

Viewers also liked

다함께, FluxUtils 한바퀴!
다함께, FluxUtils 한바퀴!다함께, FluxUtils 한바퀴!
다함께, FluxUtils 한바퀴!
우영 주
 

Viewers also liked (7)

엔지니어 관점에서 바라본 데이터시각화
엔지니어 관점에서 바라본 데이터시각화엔지니어 관점에서 바라본 데이터시각화
엔지니어 관점에서 바라본 데이터시각화
 
GDG DevFest 2017 Seoul 프론트엔드 모던 프레임워크 낱낱히 파헤치기
 GDG DevFest 2017 Seoul 프론트엔드 모던 프레임워크 낱낱히 파헤치기 GDG DevFest 2017 Seoul 프론트엔드 모던 프레임워크 낱낱히 파헤치기
GDG DevFest 2017 Seoul 프론트엔드 모던 프레임워크 낱낱히 파헤치기
 
파이썬 리액티브하게 짜기 - PyCon Korea 2017
파이썬 리액티브하게 짜기 - PyCon Korea 2017파이썬 리액티브하게 짜기 - PyCon Korea 2017
파이썬 리액티브하게 짜기 - PyCon Korea 2017
 
역시 Redux
역시 Redux역시 Redux
역시 Redux
 
다함께, FluxUtils 한바퀴!
다함께, FluxUtils 한바퀴!다함께, FluxUtils 한바퀴!
다함께, FluxUtils 한바퀴!
 
Facebook은 React를 왜 만들었을까?
Facebook은 React를 왜 만들었을까? Facebook은 React를 왜 만들었을까?
Facebook은 React를 왜 만들었을까?
 
AngularJS 2, version 1 and ReactJS
AngularJS 2, version 1 and ReactJSAngularJS 2, version 1 and ReactJS
AngularJS 2, version 1 and ReactJS
 

Similar to Dealing with Python Reactively - PyCon Korea 2017

Functional Reactive Programming / Compositional Event Systems
Functional Reactive Programming / Compositional Event SystemsFunctional Reactive Programming / Compositional Event Systems
Functional Reactive Programming / Compositional Event Systems
Leonardo Borges
 
C++ Function
C++ FunctionC++ Function
C++ Function
Hajar
 
DataMiningReport
DataMiningReportDataMiningReport
DataMiningReport
?? ?
 
JLK Chapter 5 – Methods and ModularityDRAFT January 2015 Edition.docx
JLK Chapter 5 – Methods and ModularityDRAFT January 2015 Edition.docxJLK Chapter 5 – Methods and ModularityDRAFT January 2015 Edition.docx
JLK Chapter 5 – Methods and ModularityDRAFT January 2015 Edition.docx
vrickens
 
Programming Languages Implementation and Design. .docx
  Programming Languages Implementation and Design. .docx  Programming Languages Implementation and Design. .docx
Programming Languages Implementation and Design. .docx
aryan532920
 

Similar to Dealing with Python Reactively - PyCon Korea 2017 (20)

While loop
While loopWhile loop
While loop
 
Intro To C++ - Class #17: Pointers!, Objects Talking To Each Other
Intro To C++ - Class #17: Pointers!, Objects Talking To Each OtherIntro To C++ - Class #17: Pointers!, Objects Talking To Each Other
Intro To C++ - Class #17: Pointers!, Objects Talking To Each Other
 
Python_Functions.pdf
Python_Functions.pdfPython_Functions.pdf
Python_Functions.pdf
 
C++ Functions
C++ FunctionsC++ Functions
C++ Functions
 
Introduction To Python.pptx
Introduction To Python.pptxIntroduction To Python.pptx
Introduction To Python.pptx
 
RxJava 2 Reactive extensions for the JVM
RxJava 2  Reactive extensions for the JVMRxJava 2  Reactive extensions for the JVM
RxJava 2 Reactive extensions for the JVM
 
Functional Reactive Programming / Compositional Event Systems
Functional Reactive Programming / Compositional Event SystemsFunctional Reactive Programming / Compositional Event Systems
Functional Reactive Programming / Compositional Event Systems
 
C++ Course - Lesson 1
C++ Course - Lesson 1C++ Course - Lesson 1
C++ Course - Lesson 1
 
2 Functions2.pptx
2 Functions2.pptx2 Functions2.pptx
2 Functions2.pptx
 
C++ Function
C++ FunctionC++ Function
C++ Function
 
DataMiningReport
DataMiningReportDataMiningReport
DataMiningReport
 
Concurrency, Robustness & Elixir SoCraTes 2015
Concurrency, Robustness & Elixir SoCraTes 2015Concurrency, Robustness & Elixir SoCraTes 2015
Concurrency, Robustness & Elixir SoCraTes 2015
 
How To Use IO Monads in Scala?
 How To Use IO Monads in Scala? How To Use IO Monads in Scala?
How To Use IO Monads in Scala?
 
Incredible Machine with Pipelines and Generators
Incredible Machine with Pipelines and GeneratorsIncredible Machine with Pipelines and Generators
Incredible Machine with Pipelines and Generators
 
C++ Homework Help
C++ Homework HelpC++ Homework Help
C++ Homework Help
 
85ec7 session2 c++
85ec7 session2 c++85ec7 session2 c++
85ec7 session2 c++
 
JLK Chapter 5 – Methods and ModularityDRAFT January 2015 Edition.docx
JLK Chapter 5 – Methods and ModularityDRAFT January 2015 Edition.docxJLK Chapter 5 – Methods and ModularityDRAFT January 2015 Edition.docx
JLK Chapter 5 – Methods and ModularityDRAFT January 2015 Edition.docx
 
Programming Languages Implementation and Design. .docx
  Programming Languages Implementation and Design. .docx  Programming Languages Implementation and Design. .docx
Programming Languages Implementation and Design. .docx
 
Giorgio zoppi cpp11concurrency
Giorgio zoppi cpp11concurrencyGiorgio zoppi cpp11concurrency
Giorgio zoppi cpp11concurrency
 
Functions
FunctionsFunctions
Functions
 

More from Kenneth Ceyer

More from Kenneth Ceyer (11)

이미지 프로세싱 in Python Open Source - PYCON KOREA 2020
이미지 프로세싱 in Python Open Source - PYCON KOREA 2020이미지 프로세싱 in Python Open Source - PYCON KOREA 2020
이미지 프로세싱 in Python Open Source - PYCON KOREA 2020
 
정적 컨텐츠 제너레이터 GatsbyJS에 대해서 알아봅시다.
정적 컨텐츠 제너레이터 GatsbyJS에 대해서 알아봅시다.정적 컨텐츠 제너레이터 GatsbyJS에 대해서 알아봅시다.
정적 컨텐츠 제너레이터 GatsbyJS에 대해서 알아봅시다.
 
LP(linear programming) Algorithm
LP(linear programming) AlgorithmLP(linear programming) Algorithm
LP(linear programming) Algorithm
 
AI 연구자를 위한 클린코드 - GDG DevFest Seoul 2019
AI 연구자를 위한 클린코드 - GDG DevFest Seoul 2019AI 연구자를 위한 클린코드 - GDG DevFest Seoul 2019
AI 연구자를 위한 클린코드 - GDG DevFest Seoul 2019
 
하둡 에코시스템 위에서 환상적인 테이크오프 - DSTS 2019
하둡 에코시스템 위에서 환상적인 테이크오프 - DSTS 2019 하둡 에코시스템 위에서 환상적인 테이크오프 - DSTS 2019
하둡 에코시스템 위에서 환상적인 테이크오프 - DSTS 2019
 
AllReduce for distributed learning I/O Extended Seoul
AllReduce for distributed learning I/O Extended SeoulAllReduce for distributed learning I/O Extended Seoul
AllReduce for distributed learning I/O Extended Seoul
 
gRPC와 goroutine 톺아보기 - GDG Golang Korea 2019
gRPC와 goroutine 톺아보기 - GDG Golang Korea 2019gRPC와 goroutine 톺아보기 - GDG Golang Korea 2019
gRPC와 goroutine 톺아보기 - GDG Golang Korea 2019
 
How to use vim
How to use vimHow to use vim
How to use vim
 
Test and refactoring
Test and refactoringTest and refactoring
Test and refactoring
 
Deep dive into Modern frameworks - HTML5 Forum 2018
Deep dive into Modern frameworks - HTML5 Forum 2018Deep dive into Modern frameworks - HTML5 Forum 2018
Deep dive into Modern frameworks - HTML5 Forum 2018
 
우아하게 준비하는 테스트와 리팩토링 - PyCon Korea 2018
우아하게 준비하는 테스트와 리팩토링 - PyCon Korea 2018우아하게 준비하는 테스트와 리팩토링 - PyCon Korea 2018
우아하게 준비하는 테스트와 리팩토링 - PyCon Korea 2018
 

Recently uploaded

Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
WSO2
 

Recently uploaded (20)

Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024
 
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUKSpring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Cyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdfCyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdf
 

Dealing with Python Reactively - PyCon Korea 2017

  • 1. Dealing with Python Reactively PyCon Korea 2017 Kenneth
  • 5. What is reactive programming? CH 1. Reactive Programming The new paradigm that focused on the asynchronous data flow
  • 7. Key keyword #1 CH 1. Reactive Programming Asynchronous It can be received the data that is not guaranteed In the asynchronous environment sequentially, And also it can be processed the data flexible.
  • 8. Key keyword #2 CH 1. Reactive Programming Reactive It is not executed if there is no operation (input) from the outside.
  • 9. Key keyword #3 CH 1. Reactive Programming Lightweight Data flow can be subdivided for each purpose, And also it can be merged again. This makes it possible to reduce the weight.
  • 10. The data flows. CH 1. Reactive Programming
  • 11. However it does not flow at the same time. So we can not guarantee that the data always comes. CH 1. Reactive Programming
  • 12. It can not be easy to process the data that comes every another times. CH 1. Reactive Programming .next() .subscribe()
  • 13. Controlling multiple data flows. Reactive programming makes it possible. CH 1. Reactive Programming The data that comes from each different times concurrently, To be sequentially
  • 14. It only see the data flows. That’s why it’s intuitive. CH 1. Reactive Programming Map Filter Merge Reduce On Complete On Error Retry Skip Buffer
  • 16. ReactiveX (RX) CH 2. RxPy Microsoft announced `Volta` project in 2007 It is officially known as `Reactive Extensions` in 2009 It was gradually released as open source since 2012
  • 17. def observer_generator(observer): # It passes the string “hello” through the observer. observer.on_next("hello") # Likewise, it passes the string "world!" through the observer. observer.on_next("world!") def main(): # Create an observer, passes it to a predefined function, and receives an object that can receive it. observable = Observable.create(observer_generator) # Receive the observer, At this time the observer read the variable that passed at on_next. # Oh! After the below subscribe is started, the above observer_generator will be executed. observable.subscribe(on_next=lambda value: print(value)) hello_world.py observable.create (Create an observer) observer_generator observer
  • 18. def observer_generator(observer): # It passes the string “hello” through the observer. observer.on_next("hello") # Likewise, it passes the string "world!" through the observer. observer.on_next("world!") def main(): # Create an observer, passes it to a predefined function, and receives an object that can receive it. observable = Observable.create(observer_generator) # Receive the observer, At this time the observer read the variable that passed at on_next. # Oh! After the below subscribe is started, the above observer_generator will be executed. observable.subscribe(on_next=lambda value: print(value)) hello_world.py observable 1. next(‘hello’) 2. next(‘world!’) observer 1. print(‘hello’) 2. print(‘world!’) It passes the data through on_next Print the message that received from on_next
  • 19. from rx import Observable, Observer class PrintObserver(Observer): def on_next(self, value): print('on_next value:%s’ % (value)) def on_completed(self): print('on_completed !') def on_error(self, value): print('on_error value:%s’ % (value)) def observer_generator(observer): observer.on_next(“break") observer.on_next(“the ice!") while True: message = input() if message: observer.on_next(message) else: observer.on_completed() break def main(): observable = Observable.create(observer_generator) observable.subscribe(PrintObserver()) ice_breaking.py Observable (Data forwarder) Observable (Data receiver) subscribe() next(‘break’) next(‘the ice!’) next(‘message’) print() print() print() on_next on_next on_next completed() on_completed print() 1. You can expand incoming messages by using Predefined object in Subscribe method.
  • 21. Coroutine? CH 3. Coroutine / Generator Unlike functions, Routines whose parents are “equivalent” to the called function. Python only: Coroutine can process only the received data.
  • 22. Coroutine vs General routine CH 3. Coroutine / Generator General Routine Function call Return Parameters Result Coroutine Function call Parameters Yield Yield Yield Main code Main code Calculating Calculating Calculating Send Send Send
  • 23. Use Case CH 3. Coroutine / Generator Init Data Caller Coroutine 2. Wait for the caller's input via yield (Will be returned to caller code lines) 1. Inserting initial data to apply to coroutines 3. If you have input to the caller, return to the coroutine code and execute the logic. If yield appearsin the logic, it returns to the parent code again. (repeat) next() Yield Yield 4. Finally, the caller ends the coroutine. Close
  • 24. Generator? CH 3. Coroutine / Generator If Coroutine is a gourmand, The Generator is the giving tree. A generator is a `generator` that generates data through yield.
  • 25. Do you know range function? CH 3. Coroutine / Generator def main(): # Use the range function to insert each value from 0 to 2 # into value and repeat it three times. for value in range(3): print(u’current value %d' % (value)) OUTPUT: current_value 0 current_value 1 current_value 2
  • 26. Making range function by using Generator. CH 3. Coroutine / Generator # It is the range function created by using the Generator. def custom_range(number): index = 0 while(index < number): # At this point, we go back to the parent that called this function, # Pass the value, and proceed to the parent's logic until we call this function again. # This is the heart of the generator. Remember this! yield index index += 1
  • 27. coroutine_generator.py def main(): # Let's try to use the existing range function. for value in range(3): print(u'original range %d' % (value)) # Insert a line escaping for the division. print(u'n') # Let's try the function we just created. for value in custom_range(3): print(u'custom range %d' % (value)) OUTPUT original range 0 original range 1 original range 2 custom range 0 custom range 1 custom range 2
  • 28. Use Case CH 3. Coroutine / Generator Large Data Memory Process yield 1. In a real-time cursor, yield returns every 500 datasets. 2. Actually there are only 500 data in memory, so there is out of memory problem. 3. When 500 data are processed and the process is finished, 500 data will be emptied from the memory. Likewise, there is no out of memory problem. 4. At the end of the process, it again gets 500 data from Large Data.
  • 29. Conclusion about Generator CH 3. Coroutine / Generator Data that comes in real time can be used to stabilize the memory by using the generator! (Performance difference is insignificant)
  • 30. What is the difference Between Coroutine and Generator? CH 3. Coroutine / Generator Corutine Function call Parameters Yield Yield Yield Main code Calculating Calculating Calculating Send Send Generator Function call Parameters Yield Yield Yield Main code Calculating Calculating Calculating Return Return Return Send