可连接的observable上的RxJava重新连接不起作用

时间:2017-12-03 13:32:56

标签: java kotlin rx-java

嗨,大家好。我试图用RxJava制作某种MVC。所以这个想法是 制作一些永远订阅的常量订阅 一些可观察的。此外,可以随时重新启动此可观察项以重新运行,例如网络呼叫。我尝试使用此代码来测试此功能:

<?php
if (isset($_POST["key"])) {

    $conn = new mysqli(host:"localhost", username:"root", passwd:"", dbname:"serije_bp");

    $name = $conn->real_escape_string($_POST["naziv"]);
    $opis = $conn->real_escape_string($_POST["opis"]);
    $ocjena = $conn->real_escape_string($_POST["ocjena"]);

    if ($_POST["key"] == "dodajNovu") {
        $sql = $conn->query(query: "SELECT id FROM serije WHERE naziv = '$naziv'");
        if ($sql->num_rows > 0)
            exit("TV serija je vec unesena!");
        else {
            $conn->query(query: "INSERT INTO serija (naziv, opis, ocjena)
                                VALUES ('$naziv', '$opis', '$ocjena')");
            exit("TV serija je uspjesno unesena!");
        }
    }
}

这就是我的预期:

class Main {
    companion object {
        @JvmStatic
        fun main(args: Array<String>) {
            val obs = Observable.interval(1, TimeUnit.SECONDS, Schedulers.io())
                .publish()

            val s1 = obs
                .doOnUnsubscribe { System.out.println("s1 unsubscribed") }
                .subscribe { System.out.println("first: $it") }

            val s = obs.connect()

            Thread.sleep(4000)

            System.out.println("unsubscribe")
            s.unsubscribe()

            Thread.sleep(1000)

            System.out.println("connect")
            val obsS2 = obs.connect()

            System.out.println("isUnsubscribed: ${s1.isUnsubscribed}")

            Thread.sleep(10000)
        }
    }
}

这是实际结果:

first: 0
first: 1
first: 2
unsubscribe
connect
isUnsubscribed: false
first: 0
first: 1
...
Process finished with exit code 0

我发现了一些帖子(RxJava - ConnectableObservable, disconnecting and reconnectinghttps://github.com/Froussios/Intro-To-RxJava/issues/18),人们说这是一个错误,但这个错误存在很长时间。

所以问题是:它真的是一个错误吗?如果没有,我怎么能实现这种行为?

编辑: 测试版本1.3.4,1.2.10,1.1.10,1.0.10

1 个答案:

答案 0 :(得分:1)

这不是bug,而是RxJava ConnectableObservable的属性:如果你unsubscribe连接,以前订阅的消费者将被弹出,即使重新连接也不会再收到任何其他事件。

通过使用PublishSubject,然后订阅并取消订阅实际来源,您可以实现与Rx.NET行为类似的效果:

PublishSubject subject = PublishSubject.create();

subject.subscribe(System.out::println);

Subscription s = source.subscribe(subject::onNext);

s.unsubscribe();

Subscription s2 = source.subscribe(subject::onNext);