Android Workmanager获得工人课程的参考

发布于 2025-02-12 02:21:19 字数 957 浏览 1 评论 0原文

我面临以下问题:有我的课程继承coroutineworker。该工人的逻辑已经足够复杂,实际上dowork()调用内部其他例程和捕获(collect)的结果几个state> state> stateflow s ,例如:

   override suspend fun doWork(): Result {
      //blah-blah
        withContext(Dispatchers.Default) {
            _scanResultState.collectLatest {
                //blah-blah
            }
        }
      return ...
   }

问题:

  1. 我可以以某种方式返回/将收集的stateflow值(值是简单的原始对象)到worker.result.result
  2. 或作为选项 - 我如何在其他类中聆听/收集stateflow - 在我的worker之外?

由于,workerworkmanager实例化的类 - 我无法参考worker的具体实例。例如,在服务中我可以参考实例通过绑定服务< /a>,但如果有工人,看来这是不可能的。

有什么想法吗?

I'm facing following problem: there's my class which inherits CoroutineWorker. Logic of this worker is complicated enough, in fact doWork() calls bunch of other routines inside and catches (collect) results of several StateFlows, like:

   override suspend fun doWork(): Result {
      //blah-blah
        withContext(Dispatchers.Default) {
            _scanResultState.collectLatest {
                //blah-blah
            }
        }
      return ...
   }

Questions:

  1. Can I somehow return/put collected StateFlow values (values are simple primitive objects) to Worker.Result?
  2. Or as an option - how could I listen/collect those StateFlow in other class - outside of my Worker?

Since, Worker class instantiated by WorkManager - I can't have a reference to concrete instance of Worker. E.g. in Service I could have reference to instance through bound Services, but in case of WorkManager looks like it's impossible.

Any ideas?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

不醒的梦 2025-02-19 02:21:20

好吧,如果您想分享从工人课程到应用程序的流程,则可以使用房间数据库为此,例如,假设您想共享流程&lt; list&gt;从您的Worker实现您需要遵循以下步骤:

  1. 首先在房间数据库中创建book Entity
  2. 第二个在您的dao中添加一个函数,该函数返回流程&lt; list&gt;。
  3. 第三收集您的应用中的流量(查看模型,存储库,片段...)。
  4. 最后,在您的Worker中继续将书籍添加到您的房间数据库中。

通过这4个步骤,您将能够在任何其他类中从Worker中收集数据。

我希望我的答案清晰有用:D

Well if you want to share a flow from your Worker class to your app, you can use room database for that, for example let's say that you want to share a Flow<List> from your Worker to achieve that you need to follow these steps:

  1. First create a Book Entity in your room database.
  2. Second add a function in your Dao that returns a Flow<List>.
  3. Third collect that flow in your app (view model, repository, fragment...).
  4. Finally in your Worker keep adding books to your room database.

With these 4 steps you will be able to collect data from Worker in any other class.

I hope that my answer was clear and helpful :D

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文