Create a custom dialog with callback in Kotlin - android

I try to create a custom dialog and call it with a callback. Maybe it's not best practice but i dont have an idea to solve it better. This is the dialog:
private fun showDialog(header: String, message: String, callback: Callback? = null) {
val dialog = Dialog(this)
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE)
dialog.setCancelable(false)
dialog.setContentView(R.layout.alert_layout)
val body = dialog.findViewById(R.id.text) as TextView
val title = dialog.findViewById(R.id.title) as TextView
body.text = message
title.text = header
val yesBtn = dialog.findViewById(R.id.button) as Button
//val noBtn = dialog.findViewById(R.id.noBtn) as TextView
yesBtn.setOnClickListener {
dialog.dismiss()
if(callback != null) {
callback // Here i want execute the callback
}
}
//noBtn.setOnClickListener { dialog.dismiss() }
dialog.show()
}
This is my callback and how i call the dialog:
val callback: Callback = object:Callback {
fun run() {
println("Callback executed")
}
}
showDialog("My Title", "My Text", callback)
My opinion was to call the callback as an object like
callback.run()
My question:
Should my code working and how do i call my callback, because callback.run() seems not working.

Instead of a Callback you can pass a Kotlin lambda function.
private fun showDialog(header: String, message: String, callback: (() -> Unit)? = null) {
...
yesBtn.setOnClickListener {
callback?.invoke() // Call that function
dismiss()
}
...
}
You can pass this lambda to showDialog by using a trailing lambda syntax.
showDialog("My Title", "My Text") {
println("Callback executed")
}

Related

Class cast exception between parent and child classes

I waas develop an app in kotlin, when I get to the following error:
rise by the following check in the first line:
(it.responseBase as ValidateOtpResponse).let {resp -> // error rise here
if (resp.code == "200") {
val sucessDialog = GenericDialog(
context = requireContext(),
icon = R.drawable.ic_tick_green,
title = getString(R.string.change_password_title),
subtitle = getString(R.string.password_change_sucess),
buttonText = getString(R.string.understand),
cancelable = true,
clickListener = { (activity as DashboarActivity).redirectToLogin() }
)
sucessDialog.show(requireFragmentManager(), "sucess_otp_dialog")
} else {
showOtpError().also {
(activity as DashboarActivity).redirectToLogin()
}
}
}
and the arquitecture of the clases in the app is this:
data class ValidateOtpResponse(
#SerializedName("code")
val code: String
) : Serializable, ResponseBase()
and their parent:
open class ResponseBase : Serializable
Have this any sense? Because I being using this kind of cast along the app, and it's works until now
So if you can throw some light into this issue, take thanks in advance !
I try to apply the change which suggest Slaw, and Hakshay, and I've done something like this at repository level, which I guess it should works, but it doesn't:
Activity.class
(it.responseBase).let {resp ->
if ((resp as ValidateOtpResponse).code == "200") {
val sucessDialog = GenericDialog(
context = requireContext(),
icon = R.drawable.ic_tick_green,
title = getString(R.string.change_password_title),
subtitle = getString(R.string.password_change_sucess),
buttonText = getString(R.string.understand),
cancelable = true,
clickListener = { (activity as DashboarActivity).redirectToLogin() }
)
sucessDialog.show(requireFragmentManager(), "sucess_otp_dialog")
} else {
showOtpError().also {
(activity as DashboarActivity).redirectToLogin()
}
}
}
Repository.class
override fun onResponse(
call: Call<ValidateOtpResponse>,
response: Response<ValidateOtpResponse>
) {
/**
* We set as response the code, which tells if the call works: 200: OK - 400: KO
*/
if(response.isSuccessful){
response.let {
var value: WrapperResponse<ValidateOtpResponse> = WrapperResponse(response.body() as ValidateOtpResponse, ErrorBase(ErrorBase.ErrorType.NON_ERROR))
(value.responseBase as ValidateOtpResponse).code = response.code().toString()
Log.d("pass", "code after change: ${(value.responseBase as ValidateOtpResponse).code}")
validateChangePasswordOtpLD.postValue(value)
}
}else{
var error : ErrorBase
response.let {
error = ErrorBase(it.errorBody()!!.string(), it.code(), ErrorBase.ErrorType.STRING)
}
validateChangePasswordOtpLD.postValue((WrapperResponse(ResponseBase(), error)))
}
}
override fun onFailure(call: Call<ValidateOtpResponse>, t: Throwable) {
validateChangePasswordOtpLD.postValue(WrapperResponse(ResponseBase(), ErrorBase()))
}
I try to set the response from the API, and then modify the atribute of the response before set to the LD.
Although this changes, I still getting the cast exception when I try to recover the data into the activity.
Your response is of type ResponseBase which is the superclass. You are trying to cast it to type ValidateOtpResponse which is a subclass. You would not be able to cast an object of superclass into an object of the subclass.
For example:
You need to fetch the response of type ValidateOtpResponse.

Return a value from a Listeners onSuccess() in Kotlin (Android)

I try these tutorials: https://github.com/docusign/mobile-android-sdk/blob/master/README.md, especially the function getUserSignatureInfo. In this function a REST API call (userSignaturesGetUserSignature) is made.
In my code below I try to return a value (userSignatureId) I get from REST API. I understand, it's impossible this way, because onSuccess() will be invoked later as the outer function getUserSignatureInfo() returns.
I want to call getUserSignatureInfo() from a Fragments onActivityCreated() and use this value on creating a RecyclerView.Adapter.
The question is, what is the (best practice) way to do something like this: make a REST API call, wait for response, and use the response in further code.
// my Fragment
...
...
val userSignatureId = getUserSignatureInfo()
recyclerView.adapter = createMyAdapter(userSignatureId)
...
...
// function where the REST API call is made
fun getUserSignatureInfo(context: Context) : String {
val eSignApiDelegate = DocuSign.getInstance().getESignApiDelegate()
val usersApi = eSignApiDelegate.createApiService(UsersApi::class.java)
val authDelegate = DocuSign.getInstance().getAuthenticationDelegate()
val user = authDelegate.getLoggedInUser(context)
var userSignatureId = ""
eSignApiDelegate.invoke(object : DSESignApiListener {
override fun <T> onSuccess(response: T?) {
if (response is UserSignaturesInformation) {
val userSignature = (response as UserSignaturesInformation).getUserSignatures().get(0)
Log.d(TAG, "Signature Id: " + userSignature.signatureId);
// My problem: this assignment is useless
// because the outer function getUserSignatureInfo()
// returns earlier as onSuccess()
userSignatureId = userSignature.signatureId
}
}
override fun onError(exception: DSRestException) {
// TODO: Handle error
}
}) {
usersApi!!.userSignaturesGetUserSignature(user.accountId, user.userId, "signature")
}
// This is my problem: userSignatureId is empty because
// onSuccess() fires later as this function returns
return userSignatureId
}
Thank you much!
You could pass a callback into getUserSignatureInfo(), for example
fun getUserSignatureInfo(context: Context, callback: (String)->Unit) : String {
val eSignApiDelegate = DocuSign.getInstance().getESignApiDelegate()
val usersApi = eSignApiDelegate.createApiService(UsersApi::class.java)
val authDelegate = DocuSign.getInstance().getAuthenticationDelegate()
val user = authDelegate.getLoggedInUser(context)
eSignApiDelegate.invoke(object : DSESignApiListener {
override fun <T> onSuccess(response: T?) {
if (response is UserSignaturesInformation) {
val userSignature = (response as UserSignaturesInformation).getUserSignatures().get(0)
Log.d(TAG, "Signature Id: " + userSignature.signatureId);
// return the value in the callback
callback(userSignature.signatureId)
}
}
When you want to use the string value from another class,
getUserSignatureInfo(context) { id ->
Log.d("test", id)
}

How to resolve the error "LifecycleOwners must call register before they are STARTED"

I am using registerForActivityResult for google sign in implementation in my development. Everything was working fine until I upgraded my fragment dependency to 1.3.0-beta01. The application current crash with the error
java.lang.IllegalStateException: LifecycleOwner SignupChoicesFragment{8e0e269} (193105b9-afe2-4941-a368-266dbc433258) id=0x7f090139} is attempting to register while current state is RESUMED. LifecycleOwners must call register before they are STARTED.
I have used the function before oncreate using lazy loading but it wont work still.
class SignupChoicesFragment : DaggerFragment() {
#Inject
lateinit var viewModelProviderFactory: ViewModelFactory
val userViewModel: UserViewModel by lazy {
ViewModelProvider(this, viewModelProviderFactory).get(UserViewModel::class.java)
}
#Inject
lateinit var mGoogleSignInClient:GoogleSignInClient
val arg:SignupChoicesFragmentArgs by navArgs()
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_signup_choices, container, false)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
google_sign_in_button.setOnClickListener {
val intent = mGoogleSignInClient.signInIntent
val launcher = registerForActivityResult(ActivityResultContracts.StartActivityForResult(), ActivityResultCallback {result->
if (result.resultCode == Activity.RESULT_OK) {
val task = GoogleSignIn.getSignedInAccountFromIntent(result.data)
task.addOnCompleteListener {
if (it.isSuccessful) {
val account: GoogleSignInAccount? =
it.getResult(ApiException::class.java)
val idToken = it.result?.idToken
val email = account?.email
val lastName = account?.familyName
val firstName = account?.givenName
val otherName = account?.displayName
val imageUrl = account?.photoUrl
val category = arg.category
val newUser = User()
newUser.firstName = firstName
newUser.lastName = lastName
newUser.otherName = otherName
newUser.category = category
newUser.email = email
newUser.imageUrl = imageUrl.toString()
userViewModel.currentUser = newUser
newUser.token = idToken
i(title, "idToken $idToken")
requireActivity().gdToast("Authentication successful", Gravity.BOTTOM)
val action = SignupChoicesFragmentDirections.actionSignupChoicesFragmentToEmailSignupFragment()
action.newUser = newUser
goto(action)
} else {
requireActivity().gdToast(
"Authentication Unsuccessful",
Gravity.BOTTOM
)
Log.i(title, "Task not successful")
}
}
} else {
Log.i(title, "OKCODE ${Activity.RESULT_OK} RESULTCODE ${result.resultCode}")
}
}).launch(intent)
}
}
For me, the issue was that I was calling registerForActivityResult within an onClickListener which was only invoked on clicking a button (the app at this point is in state RESUMED). Moving the call outside the button's onClickListener and into the Activity's onCreate method fixed it.
quote from documentation
registerForActivityResult() is safe to call before your fragment or activity is created, allowing it to be used directly when declaring member variables for the returned ActivityResultLauncher instances.
Note: While it is safe to call registerForActivityResult() before your fragment or activity is created, you cannot launch the ActivityResultLauncher until the fragment or activity's Lifecycle has reached CREATED.
so to solve your issue move your register call outside the onCreate() and put it in fragment scope, and on google_sign_in_button click-listener call launch function
Note: if you are using Kotlin-Android-Extention move your click-listener call to onViewCreated()
If you are using a Fragment, please make sure that you are NOT performing the registerForActivityResult on the activity. Fragments also have a registerForActivityResult and that's the one you should use.
you must remove val launcher = registerForActivityResult... out of the setOnClickListener, then save it in a variable, in your example is launcher and in the setOnClickListener execute the variable with .launch, in your example es launcher.
your code would look like this
google_sign_in_button.setOnClickListener {
val intent = mGoogleSignInClient.signInIntent
launcher.launch(intent)
}
private val launcher = registerForActivityResult(ActivityResultContracts.StartActivityForResult(), ActivityResultCallback {result->
if (result.resultCode == Activity.RESULT_OK) {
val task = GoogleSignIn.getSignedInAccountFromIntent(result.data)
task.addOnCompleteListener {
if (it.isSuccessful) {
val account: GoogleSignInAccount? =
it.getResult(ApiException::class.java)
val idToken = it.result?.idToken
val email = account?.email
val lastName = account?.familyName
val firstName = account?.givenName
val otherName = account?.displayName
val imageUrl = account?.photoUrl
val category = arg.category
val newUser = User()
newUser.firstName = firstName
newUser.lastName = lastName
newUser.otherName = otherName
newUser.category = category
newUser.email = email
newUser.imageUrl = imageUrl.toString()
userViewModel.currentUser = newUser
newUser.token = idToken
i(title, "idToken $idToken")
requireActivity().gdToast("Authentication successful", Gravity.BOTTOM)
val action = SignupChoicesFragmentDirections.actionSignupChoicesFragmentToEmailSignupFragment()
action.newUser = newUser
goto(action)
} else {
requireActivity().gdToast(
"Authentication Unsuccessful",
Gravity.BOTTOM
)
Log.i(title, "Task not successful")
}
}
} else {
Log.i(title, "OKCODE ${Activity.RESULT_OK} RESULTCODE ${result.resultCode}")
}
})
Source : https://medium.com/codex/android-runtime-permissions-using-registerforactivityresult-68c4eb3c0b61
registerForActivityResult() is safe to call before your fragment or activity is created, allowing it to be used directly when declaring member variables for the returned ActivityResultLauncher instances.
you should call registerForActivityResult before view created. member variables or onCreate()
If you are working with any third party library then it may happens that you can't see the "registerForActivityResult" in your code but it should be present in classes provided by that same library.
So in this case I will suggest to move out the lines which is related to that library from any listener to the onCreate method.
for example -
btnBackup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final RoomBackup roomBackup = new RoomBackup(GoogleDriveActivity.this);
roomBackup.database(LocalDataBase.getInstance(getApplicationContext()));
roomBackup.enableLogDebug(true);
roomBackup.backupIsEncrypted(false);
roomBackup.backupLocation(RoomBackup.BACKUP_FILE_LOCATION_INTERNAL);
roomBackup.onCompleteListener((success, message, exitCode) -> {
Log.d(TAG, "success: " + success + ", message: " + message + ", exitCode: " + exitCode);
if (success) roomBackup.restartApp(new Intent(getApplicationContext(), GoogleDriveActivity.class));
});
roomBackup.restore();
}
});
//// remove other code from listener and shift in onCreate
roomBackup = new RoomBackup(GoogleDriveActivity.this);
roomBackup.database(LocalDataBase.getInstance(getApplicationContext()));
roomBackup.enableLogDebug(true);
roomBackup.backupIsEncrypted(false);
roomBackup.backupLocation(RoomBackup.BACKUP_FILE_LOCATION_INTERNAL);
roomBackup.maxFileCount(5);
roomBackup.onCompleteListener((success, message, exitCode) -> {
Log.d(TAG, "success: " + success + ", message: " + message + ", exitCode: " + exitCode);
if (success) roomBackup.restartApp(new Intent(getApplicationContext(), GoogleDriveActivity.class));
});
/// you can keep only required lines in listener
btnBackup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
roomBackup.backup();
}
});
That's it!
Found the same issue and manage to get to work with some magic.
In my case, it was happening in an Activity, so I went about it as such:
//...other bits
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(binding.root)
// doing the setup here
setupViews()
}
private fun setupViews() {
val buttonLauncher = navigator.gotoScreenForResult(this) { success ->
if (success) {
setResult(Activity.RESULT_OK)
finish()
}
}
binding.myButton.setOnClickListener {
buttonLauncher.launch(Unit)
}
Where the navigator.gotoScreenForResult would look like the following:
override fun gotoScreenForResult(context: AppCompatActivity, callback: (Boolean) -> Unit): ActivityResultLauncher<Unit> {
val contract = object : ActivityResultContract<Unit, Boolean>() {
override fun createIntent(context: Context, input: Unit?): Intent {
return Intent(context, MyNextActivity::class.java)
}
override fun parseResult(resultCode: Int, intent: Intent?): Boolean {
return resultCode == Activity.RESULT_OK
}
}
return context.registerForActivityResult(contract) { callback(it) }
}
Just make sure the setupViews is done within the onCreate and not on the resume step.

How can I get my response from my POST request retrofit call to my Fragment

My goal is to capture or get a response from my viewModel into my signUp-Fragment when I click the signUp-Button and navigate to verification-Fragment if response.status is true.
When I click on my signUp button in my signUpFragment, a POST request retrofit call is made and a response is received like this :
UserResponse(message=Sign up successful. A verfication code has been sent to your email address, payload=UserPayload(country=Nigeria, createdAt=2020-04-10T10:55:06.220Z, email=osehiproductengineer#gmail.com, id=5e90508a455f70002f19b42e, isVerified=false, name=osehiase ehilen, phone=07083372454, updatedAt=2020-04-10T10:55:06.220Z, v=0), status=200, token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOiI1ZTkwNTA4YTQ1NWY3MDAwMmYxOWI0MmUiLCJpYXQiOjE1ODY1MTYxMDYsImV4cCI6MTU4NjYwMjUwNn0.H_JhBQY-3PQ6Kqk7SS0cm8RP_1mzYlD987M66_LT0PU)
I saw this response using Log; the response does not get to my signUp-Fragment.
Here is my Repository code below:
class NetworkRepository(): BaseRepository() {
val userApi = UserAPI()
val authAPI = AuthAPI()
val treeAPI = TreeAPI()
val paymentAPI = PaymentAPI()
val loginAPI = LoginAPI()
val TAG = "NETWORK REPOSITORY"
private val _networkState = MutableLiveData<NetworkState>()
val networkState: LiveData<NetworkState>
get() = _networkState
//User
suspend fun createUser(userBody: UserBody): UserResponse {
var status = UserResponse()
// Log.d("SIGNUP_RESPONSE2", "inside status:$status")
withContext(Dispatchers.IO){
try {
status = userApi.addUserAsync(userBody).await()
// Log.d("signup_Response3", "after the call:$status")
}catch (t: Throwable){
Log.e(TAG, t.message.toString())
}
}
Log.d("SIGNUP_RESPONSE", "here is the $status")
return status
}
}
Here is my viewModel code:
class UserViewModel : ViewModel(){
private val repository = NetworkRepository()
private val job = Job()
private val scope = CoroutineScope(job + Dispatchers.Main)
fun createUser(userBody: UserBody):UserResponse {
var userPayload: UserResponse = UserResponse()
// Log.d("USERVIEWMODEL_TOP", "the first response:$userPayload")
scope.launch {
// userPayload = repository.createUser(userBody)
userPayload = repository.createUser(userBody)
// Log.d("USERVIEWMODELCHCK", "speak now:$userPayload")
}
// Log.d("USERVIEWMODEL_RESPONSE", "check this userViewModelRes:$userPayload")
return userPayload
}
}
Here is my SignUp-Fragment Code:
class SignUpFragment : Fragment() {
private lateinit var viewModel: UserViewModel
private lateinit var userBody: UserBody
var captureStatus:UserResponse = UserResponse()
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
viewModel = ViewModelProvider(this).get(UserViewModel::class.java)
return inflater.inflate(R.layout.fragment_sign_up, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
signup_submit_btn.setOnClickListener {
val response = sendUser()
// Log.d("SIGNUP_FRAGMENTRES", "where is this response:$response")
if (response.status == 200) {
Log.d("SIGNUP_FRAGMENT", "wat is here:${response}")
saveUserInfo(response)
findNavController().navigate(R.id.action_signUpFragment_to_verificationFragment)
} else {
Toast.makeText(
this.context,
"${response.status}, ${response.message}",
Toast.LENGTH_SHORT
).show()
}
}
signup_have_an_account.paintFlags = Paint.UNDERLINE_TEXT_FLAG
signup_have_an_account.setOnClickListener {
findNavController().navigate(R.id.action_signUpFragment_to_loginFragment)
}
signup_back_btn.setOnClickListener {
findNavController().popBackStack()
}
}
private fun sendUser(): UserResponse {
var userBody: UserBody? = null
//verification
when {
signup_email_input.editText!!.text.isEmpty() -> {
signup_email_input.editText!!.error = "Email cannot be empty"
}
signup_phone_input.editText!!.text.isEmpty() -> {
signup_phone_input.editText!!.error = "Phone cannot be empty"
}
signup_country_input.editText!!.text.isEmpty() -> {
signup_country_input.editText!!.error = "Country cannot be empty"
}
signup_password_input.editText!!.text.isEmpty() -> {
signup_password_input.editText!!.error = "Password cannot be empty"
}
signup_password_input.editText!!.text.length < 6 -> {
signup_password_input.editText!!.error = "Password cannot be less than 6 characters"
}
signup_name_input.editText!!.text.isEmpty() -> {
signup_name_input.editText!!.error = "Name cannot be empty"
}
else -> {
val email = signup_email_input.editText!!.text.toString()
val country = signup_country_input.editText!!.text.toString()
val name = signup_name_input.editText!!.text.toString()
val password = signup_password_input.editText!!.text.toString()
val phone = signup_phone_input.editText!!.text.toString()
userBody = UserBody(country, email, false, name, password, phone)
}
}
// Log.d("USER REG", userBody.toString())
return viewModel.createUser(userBody!!)
}
private fun saveUserInfo(userResponse: UserResponse) {
this.activity?.let { Preferences.setEmail(it, userResponse.payload!!.email) }
this.activity?.let { Preferences.saveAuthToken(it, userResponse.token!!) }
}
}
userPayload = repository.createUser(userBody)
This line in your ViewModel will execute in background thread and hence is asynchronus, In order to publish "userPayload" object to your fragment, you need to make use of LiveData like this
//Define a mutablelivedata property in your ViewModel
public var userPayloadLiveData = MutableLiveData<UserResponse>()
From the co-routine inside your ViewModel you need to post your response to the livedata as such
userPayload = repository.createUser(userBody)
userPayloadLiveData.postValue(userPayload)
From your fragment you need to observe the "userPayloadLiveData" for async changes in value.
viewModel.userPayloadLiveData.observe(this, Observer { userResponse ->
//this code will run after network call and now safe to do UI stuff.
//userResponse is your response object
})
To understand more about how LiveData or MutableLiveData works please refer to androidx docs MutableLiveData
It's bad approach to instantiate variable (like: status, userPayload) with some Dummy Object, and then changing it with response from other method, then returning it via return function. You should better instantiate it with null and return the response to calling function via callback. Then if you have null you immediately now, something goes wrong.
The above approach is source of your problem. Because the createUser function is returning DummyObject, not actual object from Retrofit. To fix this, you need to delete return function from createUser method. And then add callback or higher-order function as second parameter.
Here is example of higher-order function, which is used as callback, when user is created:
createUser in ViewModel
fun createUser(userBody: UserBody, onUserCreated: (UserResponse) -> Unit) {
//Log.d("USERVIEWMODEL_TOP", "the first response:$userPayload")
scope.launch {
//userPayload = repository.createUser(userBody)
val userPayload: UserResponse = repository.createUser(userBody)
onUserCreated(userPayload)
//Log.d("USERVIEWMODELCHCK", "speak now:$userPayload")
}
}
Why this way? Because scope.launch{...} is something like closed environment and you have to get somehow userPayload from inside curly brackets scope.launch{ ... }. In your solution, you are returning userPayload from outisde of scope.launch{} which knows nothing about what happens inside {}
Also modify createUser function in your repository:
createUser in repository:
suspend fun createUser(userBody: UserBody): UserResponse {
return withContext(Dispatchers.IO) {
try {
val status = userApi.addUserAsync(userBody).await()
//Will be used as returend value.
status
} catch (t: Throwable) {
//Will be used as returned value - in case of error.
UserResponse()
}
}
}
Why? The same reason as above. You were returning status from outside of withContext(Dispatchers.IO) {}. So due to we want to return something from inside withContext(Dispatchers.IO) {} - we need to add return statement just before withContext. In this case last line from try {} or last line from catch{}(in case of error) will be used as return value for return statement before withContext(Dispatchers.IO) {}
And now you should be able to receive response in your fragment, by calling createUser function this way:
fragment
viewModel.createUser(userBody) { response ->
if (response.status == 200) {
Log.d("SIGNUP_FRAGMENT", "wat is here:${response}")
saveUserInfo(response)
findNavController().navigate(R.id.action_signUpFragment_to_verificationFragment)
} else {
Toast.makeText(
this.context,
"${response.status}, ${response.message}",
Toast.LENGTH_SHORT
).show()
}
}

How can I create a function that has when called, an addOnSuccessListener could be added to it

Not sure how to phrase this question. I would like to create a function, that when called, I can add addOnSuccessListener to it before continuing to the next one.
I know that when I have the function return a Task<Void> I can add to it the addOnSuccessListener but in the function itself, I am not sure what to return, as the operation I am executing is a simple process of saving EditText input into variables. Not sure what Task to return.
This is my function:
fun saveInput(): Task<Void> {
email = emailInput.text.toString()
phone = phoneInput.text.toString()
whatsApp = whatsAppInput.text.toString()
return //notSureWhatToReturnHere
}
And I want to be able to do something like this:
saveInput.onSuccess{
//do something
}
Something like this?
class Worker<T> {
private var successListener: ((result: T) -> Unit)? = null
fun onSuccess(result: T) {
successListener?.run { this(result) }
}
fun addSuccessListener(listener: (result: T) -> Unit): Worker<T> {
successListener = listener
return this
}
}
class MyRandomClass {
fun doSomething(variable: String): Worker<String> {
val worker: Worker<String> = Worker()
val result = variable.reversed()
worker.onSuccess(result)
return worker
}
}
//... in code
val randomClass = MyRandomClass()
randomClass.doSomething("Hello World")
.addSuccessListener {
Log.d(TAG, "Result is: $it")
}
}

Categories

Resources