0

I am relatively new to Rx and RxPy - there is one fundamental thing that I am trying to do which is access a value that I store at the end of an Observer on_completed. I have a feeling I am either missing something very obvious, or I am perhaps bending the Observable concept into something that it's not meant to be. Either way, hoping I can get some guidance on this.

I've looked over the documentation at things like materialize but they don't quite seem to match up. Have also looked into Do and Disposable but can't find many examples that are close to what I need.

import rx
from rx import operators as ops
from rx.core import Observer

if __name__ == "__main__":
    class PipelineObserver(Observer):
        def __init__(self):
            self.status = None

        def on_next(self, payload):
            print(payload)

        def on_error(self, err):
            print(err)

        def on_completed(self):
            self.status = "Done"
            return self.status

     ## This returns a disposable, not the actual value I want. Which in this case is self.status
    output = rx.from_([1, 2]).subscribe(
        PipelineObserver()
    )

    print(output) ## Hoping for "Done" which is stored in self.status, not disposable class

Is there anyway to access a value a value from the on_completed method? Short of saving something as a global variable (which seems like a bad idea to me) I'm not sure it's possible? Basically whatever it output by on_completed or something similar. Maybe Do or Finally?

1 Answers1

0

Ended up figuring it out, posting here in case anyone else runs into this. Due to this operation I am looking for being one that has to run after an observable is completed, it has to be a blocking operation. The run() function is used for this.

import rx
from rx import operators as ops
from rx.core import Observer

if __name__ == "__main__":
    class PipelineObserver(Observer):
        def __init__(self):
            self.status = None

        def on_next(self, payload):
            print(payload)

        def on_error(self, err):
            print(err)

        def on_completed(self):
            self.status = "Done"

    # First, seperate out the observer and observable:
    my_list = rx.from_([1, 2])

    my_list.subscribe(
        PipelineObserver()
    )

    # Say I want to return an integer of the count of items, I can use this:
    output = my_list.pipe(
       ops.count()
    ).run()

    print(output)
    # Notice the run command at the end of the chain.
    # Output: 2

There might be other/better ways of doing this but this will work for now!