SlideShare a Scribd company logo
1 of 32
RxPY для чайників
Василь Баран
Реактивний vs reactive
2
Рективність?
3
Реактивні розширення для Python
 RxPY – бібліотека для створення і маніпуляцій
асинхронними потоками даних
 Є портом Reactive Extensions для .NET
 Працює під Python 2.7, 3.4, PyPy і IronPython
 З коробки взаємодіє з AsyncIO, Tornado, GEvent,
Twisted, Tkinter, PyGame а також PyQt4 i PyQt5
 https://github.com/ReactiveX/RxPY/
 pip install rx
4
Асинхронний потік даних
5
Наша програма
6
Стан даних в конкретний час
7
Головні концепти
 Observer (Спостерігач)
 on_next(value)
 on_complete()
 on_error(error)
 Observable (Спостережуваний)
 subscribe(observer)
 Subject (Observer + Observable)
 Scheduler
8
Хто є хто?
9
Observer
10
class Cashier (AbstractObserver):
def on_next(self, value):
print(“Hello”, value)
Observable
.from_iterable([“Randy”, “Man”, “Woman”])
.subscribe(Cashier())
Output:
Hello Randy
Hello Man
Hello Woman
Observable
11
 Створення – from_(callback, future, iterable),
interval, repeat, timer, just…
 Трансформування – map, scan, window, group_by,
buffer, flat_map, flat_map_latest
 Фільтрування – filter, distinct, throttle, first, last, skip…
 Комбінування – and/then/when, join, merge,
combine_latest, zip, switch
 Обробка помилок – catch, retry
 Умовні та булеві операції – all, any, …
 Математичні та агрегаційні оператори –
average, count, max, min, sum …
Marbles. Map
12
http://reactivex.io/documentation/operators.html
http://rxmarbles.com/
Filter
13
Observable.from_iterable([1, 2, 3, 4, 5, 6]) 
.filter(lambda n: n % 2 == 0).map(lambda n: n*n)
Output: 1, 9, 25
Flat map
14
Observable.from_iterable([1, 2, 3]) 
.flat_map(lambda i: Observable.range(1, i))
Output: 1, 1, 2, 1, 2, 3
Buffer
15
changed_players 
.buffer_with_time(66, scheduler=scheduler) 
.filter(lambda changes: len(changes) > 0)
Scan
16
Observable.from_iterable([1, 2, 3, 4, 5, 6]) 
.map(lambda n: n*n).scan(lambda acc, n: acc + n, 0)
Output: 1, 5, 14, 30, 55, 91
Zip
17
players.zip(new_players, lambda p, ps: (ps, p)) 
.subscribe(new_player_updates)
Суб’єкти (Subject)
18
 Subject
 Observer + Observable
 ReplaySubject
 Subject + cache
 BehaviorSubject
 Subject + value
 AsyncSubject
 Observer + Observable.last()
Планувальники (Scheduler)
19
 NewThreadScheduler
 CurrentThreadScheduler
 EventLoopScheduler
 TimeoutScheduler
 HistoricalScheduler
 …
 MainLoop планувальники
 AsyncIO, Tornado, GEvent, Twisted, Tkinter, PyGame,
PyQt4/PyQt5/PySide
observe_on
20
import threading
from rx.concurrency import NewThreadScheduler, CurrentThreadScheduler
from rx.observable import Observable
def map_n(n):
print("Mapping %d in thread %d" %
(n, threading.current_thread().ident))
return n + 1
def observe(n):
print("Got result %d in thread %d" %
(n, threading.current_thread().ident))
scheduler = NewThreadScheduler()
obs = Observable.from_iterable([1, 10]) 
.map(map_n) 
.observe_on(scheduler) 
.map(map_n) 
i = obs.to_blocking().to_iterable()
[observe(x) for x in i]
Вийде щось таке
21
Mapping 1 in thread 9832
Mapping 10 in thread 9832
Mapping 2 in thread 2424
Mapping 11 in thread 2424
Got result 3 in thread 9832
Got result 12 in thread 9832
Уникайте Rx заради Rx
22
# Find packets with TCP, a dport of 80, and
# a length between 50-65
http = sub.select(lambda x:x
).where(lambda x: TCP in x
).where(lambda x: x[IP].dport == 80
).where(lambda x: int(x[IP].len) < 65
).where(lambda x: int(x[IP].len) > 50)
# знайдено в github
Тільки чисті функції
23
1. По замовчуванню круто
2. На перед не відомо в якому треді (корутині, процесі,
…) буде запускатись ф-я
3. Є метод do_action, якщо зовсім не терпиться
Побічні дії за межі RX
24
 потрібна модель – зробіть її зовнішньою
 потрібен стан – зробіть його Observable або винесіть
за RX
 потрібна бібліотека з внутрішнім станом – винесіть її
за RX, зробивши адаптер з ІО для неї
Побічні дії за межі RX
25
IO
RxPy
Side
Effects
RxPy
Як тестувати?
26
JUST
TEST
IT
Недоліки
27
 Не консистентне апі
 Неймовірно болючий дебаг
 Майже відсутня документація
 Відсутні Гарячі і Холодні спостерігачі з коробки
 Не до кінця продумана підтримка своїх
планувальників
 Просто неймовірно болючий дебаг
 Не всюди доступні методи класу як оператори
 Відсутні підказки в IDE
 Дебаг
Чому?
28
Embrace the power!
29
Реактивний маніфест
 Орієнтованість на події
 Стійкість до відмови
 Масштабованість
 Чутливість
http://www.reactivemanifesto.org/
Що читати?
30
 http://www.introtorx.com/
 http://rxmarbles.com/
 http://reactivex.io/
 http://rxwiki.wikidot.com/
 http://xgrommx.github.io/rx-
book/content/resources/articles/index.html
 http://elm-lang.org/papers/concurrent-frp.pdf
Де пробувати
31
https://github.com/vasylbo/rx.py_multiplayer
Сервер: RxPY, aiohttp
Клієнт: Coffeescript, PIXI, Bacon.js
Запитання?
32
email: vasylbo@gmail.com
linkedIn: in/vasyl-baran-6176784b

More Related Content

Featured

2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by HubspotMarius Sescu
 
Everything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTEverything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTExpeed Software
 
Product Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsProduct Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsPixeldarts
 
How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthThinkNow
 
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfAI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfmarketingartwork
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024Neil Kimberley
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)contently
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024Albert Qian
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsKurio // The Social Media Age(ncy)
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Search Engine Journal
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summarySpeakerHub
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next Tessa Mero
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentLily Ray
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best PracticesVit Horky
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project managementMindGenius
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...RachelPearson36
 

Featured (20)

2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot
 
Everything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTEverything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPT
 
Product Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsProduct Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage Engineerings
 
How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental Health
 
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfAI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
 
Skeleton Culture Code
Skeleton Culture CodeSkeleton Culture Code
Skeleton Culture Code
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie Insights
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search Intent
 
How to have difficult conversations
How to have difficult conversations How to have difficult conversations
How to have difficult conversations
 
Introduction to Data Science
Introduction to Data ScienceIntroduction to Data Science
Introduction to Data Science
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best Practices
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project management
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
 

RxPY для чайників