Issue
In the past I used "startActivityForResult" and "onActivityResult". Those methods are now deprecated. Therefore I want to use the modern alternative "registerForActivityResult".
Unfortunately, however, I cannot figure out a way to achieve the old functionality with this new model. I used to override "startActivityForResult" and "onActivityResult" of "AppCompatActivity" to run specific code before any activity was started and whenever any activity finished with a result. This was very convenient, since I didn't have to write the code for every activity launch.
As I see it now, I register the activity for a result and pass a callback to get a launcher that I can use to launch the activity later. This part I could solve by creating a function to use the launcher that always executes certain code. But there's a problem with the callback. As I see it, I would have to write this specific code into the callback of every callback I write for any activity launch.
Am I correct or am I missing something?
Solution
Theres a couple ways to do this:
1)Put the common code in its own function and just call that function in every callback. Reduces the code needed to be written to 1 line
2)Write a callback class GenericCallback. Then write your specific callback MySpecificCallback extends GenericCallback. Put the common code in the GenericCallback class and you just have to call super in the specific callback. Reduces the code to just calling super.callbackFunction, but means you can't use a lambda- you have to use a named or anonymous class. This is probably more of a Java approach though
3)Create a wrapper function for registerForActivityResult that takes a callback, and calls the real registerForActivityResult who's callback calls the common code and your callback Example:
fun registerWrapper(callback: ()->Unit) {
registerForActivityResult(() ->{
doCommonCode()
callback()
}
}
Answered By - Gabe Sechan
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.