Search code examples
rx-javareactive-programming

RxJava - Passing Observable as argument to method


Is it code smell to pass an Observabele as method argument? I use RxJava for my project. Say for example I have the following class:

public class MyClass{
//constructor and other property
public void doWork(Observable<SomeClass> obs){
//do things with the input observable
}

I don't fill comfortable passing Observable to a method but I might be wrong and it is ok?


Solution

  • Okay, so according to your comment it should be something like:

    class A {
        public final Observable<String> observable = Observable
            .just("some string")
            .replay(1).refCount()
    }
    
    class B(A aObject) {
    
        subscription = aObject
            .map { /*Do something on "some string"*/ }
            .subscribe(...)
    }
    

    Note that .replay(1).refCount() is needed if you're going to use this observable more then once (to create some other observable, and subscribe it in other place) AND if it's some getting data Observable (getting data from API/DB).

    But if observable is not "getting data from somewhere", but some time-sensitive action (like users click, scroll, etc.), it's better to use .share() instead of .replay(1).refCount()

    EDITED

    according to your comment about click: I recommend to use lib. With it your code will look like:

    class A {
        public final Observable<String> observable = someButton.clicks()
            .map { /* pass data you want here (get text from EditText)*/ }
            .share()
    }
    
    class B(Observable<String> observable) {
    
        subscription = observable
            .map { /*Do something on "some string"*/ }
            .subscribe(...)
    }
    

    BUT if you want to make it even more "RX", or you'll need to use text from editText somewhere else, You can do like:

    class A {
        public final Observable<Void> clickObservable = 
            someButton.clicks().share()
    
        public final Observable<String> textObservable = editText.textChanges()
            .map { it.toString }
            .share()
    }
    
    class B(Observable<String> textObservable, Observable<Void> clickObservable) {
    
        subscription = clickObservable
            .withLatestFrom { click, text -> text }
            .subscribe(...)
    
        // textObservable can be used more here
    }