0

I would like to change my () -> Unit parameters to Reactive Observer.

For example, I have this class:

class ExampleClass {
    var onSuccess: (() -> Unit?)? = null

    private fun doSomething(){
        //...
        onSuccess?.invoke()
        //...
    }
}

There is an 'onSuccess' Unit. I call it when it's finished with its' task.

fun doAnother(){
    val instance = ExampleClass()
    instance.onSuccess = {
        // onSuccess run
    }

}

This is the example of how I define the onSuccess.

I'm looking for a simple solution with RxJava like this.

class ExampleClass {
    var onSuccess: AnyMagic

    private fun doSomething(){
        //...
        onSuccess.notify()
        //...
    }
}

fun doAnother(){
    val instance = ExampleClass()
    instance.onSuccess
            .subscribe {
                // RxJava
            }
}

Does someone have a good simple solution to replace this Unit? Thank you

2
  • 2
    read about rxjava subjects
    – Tim
    Sep 6, 2018 at 7:23
  • 1
    you can implement it and post the solution yourself, I don't have time for it
    – Tim
    Sep 6, 2018 at 7:33

1 Answer 1

1

You may do it via RxRelay.

Get the dependency

implementation 'com.jakewharton.rxrelay2:rxrelay:2.0.0'

That's code

val myRelay: PublishRelay<String> = PublishRelay.create()

private fun doSomething() {
  myRelay.accept("Hello world")
}

fun doAnother() {
  myRelay.subscribe { s ->
    println(s)
  }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.