我有以下代码:
/**
* Request wrapped around flowable.
*/
public abstract class RequestFlowable<T> {
private final PublishProcessor<String> mPublish;
private String mName;
public RequestFlowable(String name) {
mName = name;
mPublish = PublishProcessor.create();
}
public Flowable<T> getFlowable() {
//return createAction();
return mPublish.compose(new FlowableTransformer<String, T>() {
@Override
public Publisher<T> apply(@NonNull Flowable<String> upstream) {
return createAction();
}
});
/*
return mPublish.flatMap(new Function<String, Publisher<? extends T>>() {
@Override
public Publisher<? extends T> apply(@NonNull String s) throws Exception {
return createAction();
}
});
*/
}
protected abstract Flowable<T> createAction();
public String getName() {
return mName;
}
public void start() {
mPublish.onNext("processCommand");
}
@Override
public String toString() {
return "Request: " + mName;
}
}
现在单身 #EDIT 2
public abstract class Request<T> {
private final SingleSubject<Object> mPublish;
private String mName;
public Request(String name) {
mName = name;
mPublish = SingleSubject.create();
}
public Single<T> getSingle() {
return mPublish.flatMap(o -> createAction());
}
protected abstract Single<? extends T> createAction();
public String getName() {
return mName;
}
public void start() {
mPublish.onSuccess("Start");
}
@Override
public String toString() {
return "Request: " + mName;
}
}
上面的代码在与compose一起使用时起作用,就像在上面的代码中一样,但是,如果相反我放了注释代码 - 也就是flatMap由于某种原因而不执行createAction。
上面的代码是从另一个类调用的。相应的代码附在下面(添加了类的重要部分):
public class RequestQueue implements RequestController {
private static final String TAG = RequestQueue.class.getSimpleName();
private PublishSubject<Request> mRequest;
private PublishSubject<RequestFlowable> mRequestFlowable;
@Override
public <T> Single<T> registerRequest(Request<T> request) {
mRequest.onNext(request);
return request.getSingle();
}
@Override
public <T> Flowable<T> registerRequestFlowable(RequestFlowable<T> request) {
mRequestFlowable.onNext(request);
return request.getFlowable();
}
public RequestQueue() {
mRequest = PublishSubject.create();
mRequestFlowable = PublishSubject.create();
mRequest.subscribe(this::actionOnRequest);
mRequestFlowable.subscribe(this::actionOnRequest);
}
private void actionOnRequest(Request request) {
Log.d(TAG, "actionOnRequest() called with: request = [" + request + "]");
request.start();
}
private void actionOnRequest(RequestFlowable request) {
Log.d(TAG, "actionOnRequest() called with: request = [" + request + "]");
request.start();
}
}
答案 0 :(得分:1)
(来自我的评论:)
为什么
Single
有效?
SingleSubject
保留收到的单一终端事件。由于它只能接收onSuccess
和onError
,因此它会重播&#34;对于迟到的订阅者(这也就是为什么没有分隔符ReplaySingleSubject
)。当您在onSuccess
上致电SingleSubject
时,会记住该值,并在稍后的订阅发生时重新提交,请致电createAction
。 PublishProcessor
还会记住其终端事件,但onNext
不是终端事件,因此在没有消费者的情况下被删除。
如何通过
Processor
实现所需的行为?
您可以重新组织逻辑,使用BehaviorProcessor
或ReplayProcessor.createWithSize(1)
。致电onComplete
也不会执行flatMap
功能。