RxPY
RxPY copied to clipboard
Switching scheduler to Main Thread
Hi there, just wondering how I can schedule work on specific threads, specifically the program's main thread? For example, I want to do certain map operations (here I use do_action
) on separate threads, then use on_next
the main thread. My reference to CurrentThreadScheduler seems to change once the ThreadPoolSchedulers are used - is this intended behaviour?
Here is some example code:
import reactivex as rx
from reactivex import operators as ops
from reactivex.scheduler import ThreadPoolScheduler, CurrentThreadScheduler
from threading import current_thread
print(f"starting thread: {current_thread().name}")
current_thread_scheduler = CurrentThreadScheduler()
threadpool1 = ThreadPoolScheduler(1)
threadpool2 = ThreadPoolScheduler(1)
rx.just(1).pipe(
ops.observe_on(threadpool1),
ops.do_action(lambda _: print(f"step 1: {current_thread().name}")),
ops.observe_on(threadpool2),
ops.do_action(lambda _: print(f"step 2: {current_thread().name}")),
ops.observe_on(current_thread_scheduler),
ops.do_action(lambda _: print(f"step 3: {current_thread().name}")),
).subscribe(on_next=lambda _: print(f"on_next: {current_thread().name}"))
Output:
starting thread: MainThread
step 1: ThreadPoolExecutor-0_0
step 2: ThreadPoolExecutor-1_0
step 3: ThreadPoolExecutor-1_0
on_next: ThreadPoolExecutor-1_0
Desired Output:
starting thread: MainThread
step 1: ThreadPoolExecutor-0_0
step 2: ThreadPoolExecutor-1_0
step 3: MainThread
on_next: MainThread
- OS: Windows10
- RxPY: 4.0.2
- Python version 3.9
I think in this case, current_thread_scheduler == threadpool2
is expected behavior,
current_thread means the thread on_next
is called in it
This is not possible without an event loop. See the issue #245 for more details.