可以异步/计谋被告知了Android活动的生命周期呢? [英] Can async/await be made aware of the Android activity lifecycle?
问题描述
我一直想知道异步的使用/等待产生响应的用户界面在Android上。周围使用异步功能的简单的发布/订阅包装服务(这是相当多的样板,但工程)我一直在,但我有这个痒在我身边,告诉我应该有一个更好的办法。
I've been wondering about the usage of async/await to produce responsive UIs on Android. I have been using a simple pub/sub wrapper service around the async functions (Which is quite a lot of boilerplate but works) but i've had this itch on my side that tells me there should be a better way.
对于需要包装服务源于一个事实,即在Android上的活动获得再生(破坏并重新创建)上的配置更改(设备旋转,语言的变化......),所以如果我火了一个异步函数等待回调可能生产上的破坏活动和各种不良可能来自这一点。
The need for the wrapper service stems from the fact that activities on android get "recycled" (destroyed and recreated) on configuration changes (device rotation, language change...) so if i fire an async function the await callback might be produced on a destroyed activity and all kinds of bad could originate from that.
请问异步后台莫名其妙地被告知,该code应该在不同的对象(新创建的活动),断火,而不编译黑暗魔法?
Could the async backend somehow be made aware that the code should fire off in a different object (The newly-created activity) without compiler dark magics?
依据:iOS和Android之间的共享code是所有的甜蜜和易于使用Xamarin,直到你崩溃了这个问题。这应该以某种方式解决/实现,我看到这两个平台之间通用控制器的潜力。
Rationale: Sharing code between iOS and Android is all sweet and easy using Xamarin until you crash into this problem. Should this be somehow solved/implemented, i see the potential for common controllers between both platforms.
编辑:
我已经决定要解决这个与事件总线(TinyMessenger),而据我所知,的SynchronizationContext
提出@Servy解决方案
I've decided to work around this with an Event bus (TinyMessenger) while i understand the SynchronizationContext
solution proposed by @Servy
推荐答案
当然,这是专门设计来这样做。只要你打一个等待
将检查 SynchronizationContext.Current
的值,它会发布延续这方面。如果你想有一个特殊的回调到一个特定的背景下,你只需要设置当前的背景下,以适当的乘警您的回调......但是你需要他们一个的SynchronizationContext
对象封。
Sure, it's specifically designed to do exactly that. Whenever you hit an await
it will inspect the value of SynchronizationContext.Current
, and it will post the continuation to that context. If you want a particular callback to to to a particular context, you just need to set the current context to a SynchronizationContext
object that appropriate marshals your callbacks...however you need them marshaled.
这篇关于可以异步/计谋被告知了Android活动的生命周期呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!