0

I'm primarily an iOS developer but trying to gain proficiency with Android and Kotlin.

One of the basic things I know how to do in iOS is pass a View Controller by reference to create a callback mechanism. For example, a parent VC presents a child VC, the child collects some data from the user, then calls back the parent with the data. (This is the simplest case since we might use protocols or closures to make the code more robust, but ultimately it's the same idea).

With Android, when I create a new Activity, the parameters are serialized and passed by value through the Intent. So I don't appear to have any way to set up an equivalent callback mechanism.

How does a typical Android application implement this kind of a pattern?

Thanks, Frank

Flarosa
  • 1,287
  • 1
  • 13
  • 27

2 Answers2

0

Not really sure if this is worth as an answer, but you say that:

For example, a parent VC presents a child VC, the child collects some data from the user, then calls back the parent with the data.

Well, for android, activities all operate on the same level, meaning that you can only have one activity active at a time. In order for you to then achieve some type of callback like you've mentioned here, you can make use of startActivityForResult/registerForActivityResult which provides you with similar patterns to callbacks (as you've described) to pass data between activities - start one activity for it to get data and then when it's done handle what it gives you.

Alternatively, if it's the nesting that you're looking for, and this is a way where callbacks actually are possible, you can have a look at fragments, where a fragment is a child of an activity, so you can have numerous fragments with a single containing activity, and the fragments can make use of callbacks to return data to your activity

a_local_nobody
  • 7,947
  • 5
  • 29
  • 51
0

iOS navigation is a bit more fluid compared to the Android one. The answer provided by a a_local_nobody is outdated as startActivityForResult is deprecated. Android has presented a new API for this called registerForActivityResult which basically does the same, but the code is looking more like a callback familiar on the iOS. Detailed tutorial on how to use it can be found here.

Also, consider using a single Activity and many Fragments approach. In this case you won't really need to serialize passed object, as you can create a static (companion) object in the Fragment which would have some createInstance() method where you can set the params on the created object and then push it to the FragmentManager backstack.

Bio-Matic
  • 793
  • 1
  • 8
  • 20