简体   繁体   English

使用Scala RX中的FRP管理资源

[英]Managing Resources with FRP in Scala RX

I'm using scala rx for an application. 我正在使用scala rx进行应用程序。 I have a reactive variable holding a File (which is a PDF file). 我有一个持有File的反应变量(这是一个PDF文件)。 I'm using a library to render pages from this pdf file to the screen. 我正在使用库将此pdf文件中的页面呈现到屏幕上。 Now the PDF library I'm using gives me an object (let's call it Doc ), which I can use to render single pages. 现在我正在使用的PDF库给了我一个对象(让我们称之为Doc ),我可以使用它来渲染单个页面。 But in order to render a page from a Doc object, the Doc object must be opened (thus the resource must be acquired). 但是,为了从Doc对象呈现页面,必须打开Doc对象(因此必须获取资源)。

Right now I'm loading the pdf file for each page I'm rendering anew (creating a new Doc object and closing it after rendering the single page). 现在我正在为我正在重新渲染的每个页面加载pdf文件(创建一个新的Doc对象并在渲染单个页面后关闭它)。 This makes the rendering of the page functional (given a file and a page number, return an image). 这使得页面的呈现起作用(给定文件和页码,返回图像)。

Is there a way to cling to an opened resource and close it on change in FRP in general, and for scala rx in particular? 有没有办法坚持打开资源在FRP的变化关闭它 ,特别是scala rx How would one handle this very common situation? 如何处理这种非常常见的情况?

You can simply enclose the Doc object. 您只需将Doc对象括起来即可。 So instead of render being 所以不是渲染存在

def render(file: File, pageNumber: Int): Image =  // blah blah blah

change it to: 将其更改为:

def open(file: File): (Int => Image) = {
  val doc = // call your library to read file
  (x: Int) => doc.getPage(x)
}

and then pass the function open returns to whatever page change signal you're reacting to. 然后传递函数open返回到你正在做出的任何页面更改信号。

Edit : Oh, I see, so you're saying you want it to close the file whenever the file:File signal changes to be a different file. 编辑 :哦,我明白了,所以你说你希望它在文件时关闭文件:文件信号变为另一个文件。 In that case you should be able do something like this: 在这种情况下,您应该能够做到这样的事情:

def pageGetterRx(file: Rx[File]): Rx[Int => Image] = {
  val doc: Var[Doc] = Var(null)
  val o = file.foreach { f =>
    Option(doc()).foreach(_.close)
    doc() = PdfLib.read(f)  // or however you do the reading
  }
  Rx {
    (x: Int) => doc().getPage(x)
  }
}

Edit 2 : To clarify, if you impose a "assemble network of functions phase / run the network on some signal(s) phase" distinction on FRP, the above function would be called only once; 编辑2 :为了澄清,如果你在FRP上施加“在某些信号相位上运行网络的功能组合网络”,上述功能只会被调用一次; in the assemble phase. 在组装阶段。 To say it another way, pageGetterRx (a lousy name, I'm fully aware) doesn't participate in a FR way, instead it returns a signal of lambdas that each close over one particular file and return pages from it. 换句话说, pageGetterRx (一个糟糕的名字,我完全知道)不参与FR方式,而是返回lambdas的信号,每个lambdas关闭一个特定文件并从中返回页面。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM