代码之家  ›  专栏  ›  技术社区  ›  Whimusical

如何使用IO资源装饰源中的流实例

  •  2
  • Whimusical  · 技术社区  · 7 年前

    如您所知,从IO资源生成的流需要明确地关闭。

    我希望有一个类装饰一个传递的流,但不幸的是,给定的过滤器操作是中间的,它们只是创建一个新实例,所以我失去了对关闭的控制

    Stream<T> removeNulls(Stream<T> input){
        input.filter(Objects::nonNull) //At this point, the returned pointer is a whole different stream which does not bind closing to the old one
    }
    

    try (Stream<T> myDecoratedStream = MyClass.removeNulls(myRepo.streamAll())){
       myDecoratedStrean....
    }
    
    1 回复  |  直到 7 年前
        1
  •  2
  •   Eugene    7 年前

    好像 onClose 是你想要的,比如:

    yourStream.filter(....).onClose(SomeRunnable)