我正在處理反應流時處理需要關閉的不同資源的應用程序。從flyweight自我移除資源
我有基於flyweight模式的工廠,它保持對對象的引用,並且它們實現了AutoCloseable接口。問題是我正在使用關閉()內Autocloseable類, 這裏是我的問題:什麼是最好的解決方案,以消除對工廠內關閉資源的引用?我可以拋出某種事件並在工廠中捕獲它,或者在每次可以關閉資源的操作之後,我應該遍歷引用映射並移除封閉的資源?
爲了更好的上下文: 我使用的是發出目錄事件(創建,刪除文件/目錄)的reactivex Observable,並且在每個訂閱者取消訂閱後,我正在關閉我正在使用的WatchService。
編輯#1
這裏我有多麼工廠類的樣子:
public final class Factory {
private final ConcurrentHashMap<String, ReactiveStream> reactiveStreams = new ConcurrentHashMap<>();
public ReactiveStream getReactiveStream(Path path) throws IOException {
ReactiveStream stream = reactiveStreams.get(path.toString());
if (stream != null) return stream;
stream = new ReactiveStream(path);
reactiveStreams.put(path.toString(), stream);
return stream;
}
}
這裏是如何我ReactiveStream類的樣子:
public class ReactiveStream implements AutoCloseable {
(...)
private WatchService service;
private Observable<Event> observable;
public Observable<Event> getObservable() throws IOException {
(...) // where i create observable
return observable;
}
(...)
@Override
public void close() throws IOException {
service.close();
}
}
正如你可以看到我已經得到了ReactiveStream類的引用的工廠,它在可觀察後關閉自己不會被訂閱了(我在使用doOnUnsubscribe(() - > close())的時候使用了share() )關於可觀察的,所以當沒有訂閱者時,doOnUnsubscribe將被調用)。
我的問題是,我將如何從關閉的工廠關閉ReactiveStream後將其關閉?
編輯#2
observable = Observable.fromCallable(new EventObtainer()).flatMap(Observable::from).subscribeOn(Schedulers.io()).repeat().doOnUnsubscribe(() -> {
try {
close();
} catch (IOException e) {
e.printStackTrace();
}
}).share();
這是我如何創建我觀察到的。 EventObtainer是ReactiveStream中的嵌套類,它使用WatchService,在每個用戶停止訂閱後需要關閉它。
非常不清楚的,handwavy問題。我覺得你所描述的大部分內容都與你所遇到的問題無關,而你所遇到的問題已經非常膚淺地描述了。 –
我已添加代碼段以更好地理解代碼 –
顯示您調用'doOnUnsubscribe()'的代碼。 –