首页 \ 问答 \ 循环处理期货(Deal with futures in a loop)

循环处理期货(Deal with futures in a loop)

我正在研究对数据库进行查询并占用一行的方法。 该行有一列指定了父代码(如果有的话)。 所以,我的方法有一个名为“iterate”的闭包,如果最后一行有一个父进程,那么它会执行相同的过程,最后该方法返回这些行的Sequence。 这很简单,但我必须处理期货和那些东西,我对异步编程没有多少经验。 所以。 我的问题是:

有没有办法在不使用“Await”的情况下正确地执行此方法?

/**
   * Returns all the parents of the given sector if any
   * @param childSector
   * @return
   */
  def getParents(childSector: ShopSector): Future[Option[Seq[ShopSector]]] = {
    val p = Promise[Option[Seq[ShopSector]]]
    val f: Future[Option[Seq[ShopSector]]] = p.future

    val parentsSeq: Seq[ShopSector] = Seq()

    f.onComplete( thing => println(s"Result from Iteration future: $thing") )

    def iterate(sector: ShopSector): Unit = {
      val query = for {
        c <- ShopSectors if c.id === sector.id
        p <- c.parent
      } yield p

      exists(sector.parent_id).map { exists =>
        if (exists) {
          db.run(query.result.head).map { parent =>
            println(s"Result parent: $parent")
            parentsSeq +: Seq(parent)
            iterate(parent)
          }
        } else {
          p success Option(parentsSeq)
        }
      }
    }

    iterate(childSector)

    f
  }

顺便说一句,我正在使用Slick。 并注意到这种方法效果不佳。 它返回一个空的Seq,我知道很明显这会返回它。 但印刷品工作正常并打印出正确的结果。 问题是我无法想象在所有期货完成之前有一个不会“消失”的变量的方法。

提前致谢。

编辑:好的伙计们。 问题很简单。 正如Ixx所说,parentsSeq集合并不可变。 我通过使用ListBuffer然后将其转换为序列来修复它。


I am working on a method that makes a query to the database and takes one row. This row has a column specifying the parent id if any. So, my method has a closure named "iterate" that do the same process if the last row has a parent and finally the method returns a Sequence of those rows. This is simple at first sight, but I have to deal with futures and that stuff and I do not have much experience with async programming. So. My question is:

Is there a way to do this method right without the use of "Await"?

/**
   * Returns all the parents of the given sector if any
   * @param childSector
   * @return
   */
  def getParents(childSector: ShopSector): Future[Option[Seq[ShopSector]]] = {
    val p = Promise[Option[Seq[ShopSector]]]
    val f: Future[Option[Seq[ShopSector]]] = p.future

    val parentsSeq: Seq[ShopSector] = Seq()

    f.onComplete( thing => println(s"Result from Iteration future: $thing") )

    def iterate(sector: ShopSector): Unit = {
      val query = for {
        c <- ShopSectors if c.id === sector.id
        p <- c.parent
      } yield p

      exists(sector.parent_id).map { exists =>
        if (exists) {
          db.run(query.result.head).map { parent =>
            println(s"Result parent: $parent")
            parentsSeq +: Seq(parent)
            iterate(parent)
          }
        } else {
          p success Option(parentsSeq)
        }
      }
    }

    iterate(childSector)

    f
  }

I am using Slick by the way. And notice that this method is not working well. It returns an empty Seq and I know it is obvious that this is going to return that. But the print works fine and print the right results. The thing is that I can't imagine a way to have a variable that doesn't "disappear" before all the futures are completed.

Thanks in advance.

EDIT: Okay guys. The problem was so simple. As Ixx said, the parentsSeq collection is not mutable. I fixed it by using a ListBuffer and then by converting it to a sequence.


原文:https://stackoverflow.com/questions/31761961
更新时间:2022-05-10 12:05

最满意答案

您可以使用drawable作为文本颜色,并且在drawable中可以使用选择器根据启用的状态选择颜色。 使用以下可绘制的定义作为颜色将使您的禁用菜单项灰色,其余黑色。

在例如res/drawable/default_text_colour.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_enabled="false" android:color="@android:color/darker_gray"/>
    <item android:color="@android:color/black"/>
</selector>

然后,使用drawable:

<item name="android:textColor">@drawable/default_text_colour</item>

You can use a drawable as the text colour, and in drawable you can use selector to select the colour according to enabled status. Using following drawable definition as colour will make your disabled menu items grey and the rest black.

In e.g. res/drawable/default_text_colour.xml:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_enabled="false" android:color="@android:color/darker_gray"/>
    <item android:color="@android:color/black"/>
</selector>

Then, using the drawable:

<item name="android:textColor">@drawable/default_text_colour</item>

相关问答

更多
  • 我注意到,您可以更改Firefox中禁用的文本框中的文本颜色 我认为这个问题想说的是: IE中的灰色文本结果,Fox中的红色结果。 FWIW,Opera也使灰色,而WebKit浏览器呈现红色。 这是一个纯粹的CSS问题,涉及根据操作系统的小部件集合呈现多少表单字段以及根据CSS规则多少。 这一直是跨浏览器差异很大的领域。 脚本是不相关的,尽管SO会“使用jQuery”成为每 ...
  • 尝试使用css为选择列表的first child添加颜色,如下所示 希望能帮助到你 Try adding color using css for the first child of select list as below 您可以查看此答案以获取详细信息 I finally figured this out. It just took one additional line under the ActionBarCustomTheme ...
  • CSS可以超越。 js小提琴 h3.subscribeHeader { padding-top: 0.7em; padding-bottom: 0.7em; width: 35%; margin: 0 auto; border: 1px solid #373737; } h3.subscribeHeader a:hover { color: #fafaf9; } h3.subscribeHeader:hover { background-color: #373737; } ...
  • 您可以使用drawable作为文本颜色,并且在drawable中可以使用选择器根据启用的状态选择颜色。 使用以下可绘制的定义作为颜色将使您的禁用菜单项灰色,其余黑色。 在例如res/drawable/default_text_colour.xml :
  • 你不能从元组中减去一个int。 如果你想从每个颜色元素中减去50,你可以使用 colour = tuple([c-50 for c in colour]) 如果要为每个值添加delta,并将结果约束在0到255之间,则可以使用 colour = tuple([max(0, min(255, c+delta)) for c in colour]) You can't subtract an int from a tuple. If you want to subtract 50 from each elem ...
  • 小提琴 问题出在这里: #header ul li:nth-child(3) a{ color:#C0C; } 上面的CSS规则在#header中每个 ul 每三个 li 中将颜色更改为#C0C 。 你必须对选择器更具体,并用>符号将它们分开 #header > ul > li:nth-child(3) a{ >是一个immediate child选择器。 不同的是你输入的时候 ul#menu li 它会匹配ul所有li即使那些嵌套得更深,比如
  • 只需要在Ed的答案上添加,我会建议使用键代替: ctmFile.Show(Cursor.Position); Selecteditem = lvFiles.FocusedItem.Text.ToString(); if (lvFiles.FocusedItem.ImageKey.ToString() == "Folder") { if (!ctmFile.Items.ContainsKey("Colour")) { ToolStripMenuItem Colour = n ...
  • 这应该可以解决问题。 ::-webkit-input-placeholder { color: #008752; } :-moz-placeholder { color: #008752; opacity: 1; } ::-moz-placeholder { color: #008752; opacity: 1; } :-ms-input-placeholder { ...

相关文章

更多

最新问答

更多
  • 您如何使用git diff文件,并将其应用于同一存储库的副本的本地分支?(How do you take a git diff file, and apply it to a local branch that is a copy of the same repository?)
  • 将长浮点值剪切为2个小数点并复制到字符数组(Cut Long Float Value to 2 decimal points and copy to Character Array)
  • OctoberCMS侧边栏不呈现(OctoberCMS Sidebar not rendering)
  • 页面加载后对象是否有资格进行垃圾回收?(Are objects eligible for garbage collection after the page loads?)
  • codeigniter中的语言不能按预期工作(language in codeigniter doesn' t work as expected)
  • 在计算机拍照在哪里进入
  • 使用cin.get()从c ++中的输入流中丢弃不需要的字符(Using cin.get() to discard unwanted characters from the input stream in c++)
  • No for循环将在for循环中运行。(No for loop will run inside for loop. Testing for primes)
  • 单页应用程序:页面重新加载(Single Page Application: page reload)
  • 在循环中选择具有相似模式的列名称(Selecting Column Name With Similar Pattern in a Loop)
  • System.StackOverflow错误(System.StackOverflow error)
  • KnockoutJS未在嵌套模板上应用beforeRemove和afterAdd(KnockoutJS not applying beforeRemove and afterAdd on nested templates)
  • 散列包括方法和/或嵌套属性(Hash include methods and/or nested attributes)
  • android - 如何避免使用Samsung RFS文件系统延迟/冻结?(android - how to avoid lag/freezes with Samsung RFS filesystem?)
  • TensorFlow:基于索引列表创建新张量(TensorFlow: Create a new tensor based on list of indices)
  • 企业安全培训的各项内容
  • 错误:RPC失败;(error: RPC failed; curl transfer closed with outstanding read data remaining)
  • C#类名中允许哪些字符?(What characters are allowed in C# class name?)
  • NumPy:将int64值存储在np.array中并使用dtype float64并将其转换回整数是否安全?(NumPy: Is it safe to store an int64 value in an np.array with dtype float64 and later convert it back to integer?)
  • 注销后如何隐藏导航portlet?(How to hide navigation portlet after logout?)
  • 将多个行和可变行移动到列(moving multiple and variable rows to columns)
  • 提交表单时忽略基础href,而不使用Javascript(ignore base href when submitting form, without using Javascript)
  • 对setOnInfoWindowClickListener的意图(Intent on setOnInfoWindowClickListener)
  • Angular $资源不会改变方法(Angular $resource doesn't change method)
  • 在Angular 5中不是一个函数(is not a function in Angular 5)
  • 如何配置Composite C1以将.m和桌面作为同一站点提供服务(How to configure Composite C1 to serve .m and desktop as the same site)
  • 不适用:悬停在悬停时:在元素之前[复制](Don't apply :hover when hovering on :before element [duplicate])
  • 常见的python rpc和cli接口(Common python rpc and cli interface)
  • Mysql DB单个字段匹配多个其他字段(Mysql DB single field matching to multiple other fields)
  • 产品页面上的Magento Up出售对齐问题(Magento Up sell alignment issue on the products page)