Java Flow.Subscriber - 我如何取消订阅?

时间:2018-03-01 19:29:32

标签: java publish-subscribe java-9 java.util.concurrent java-flow

我正在使用JDK 9 Flow API创建一个用户事件系统,因此我有一个房间(实现Flow.Subscriber<Notification>),它可能有很多用户,每个用户都可以随时提供(调度)更新。

当用户进入房间时,我订阅了房间user.subscribe(this)上的更新。但是没有取消订阅,当他离开房间时如何取消订阅?

public abstract class Room implements Flow.Subscriber<Notification> {
    private Flow.Subscription subscription;

    public void addUser(User user) {
        user.subscribe(this);
    }

    public void removeUser(User user) {
        // How can I unsubscribe the user?
    }

    @Override
    public void onSubscribe(final Flow.Subscription subscription) {
        this.subscription = subscription;
        subscription.request(1);
    }

    @Override
    public void onError(final Throwable throwable) {
        // ...
    }

    @Override
    public void onNext(final Notification notification) {
        // ...
        subscription.request(1);
    }

    @Override
    public void onComplete() {
        // User left
    }
}

用户类:

public class User extends SubmissionPublisher<Notification> {

    ....

    public int offer(Notification item) {
        return super.offer(item, (sub, msg) -> false);
    }
}

0 个答案:

没有答案