Machinarius
Machinarius

Reputation: 3731

Can async/await be made aware of the Android activity lifecycle?

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

Upvotes: 3

Views: 493

Answers (1)

Servy
Servy

Reputation: 203840

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.

Upvotes: 2

Related Questions