Can async/await be made aware of the Android activ

2019-05-11 05:40发布

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.

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.

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?

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.

Edit: I've decided to work around this with an Event bus (TinyMessenger) while i understand the SynchronizationContext solution proposed by @Servy

1条回答
我命由我不由天
2楼-- · 2019-05-11 05:45

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.

查看更多
登录 后发表回答