Home > Enterprise >  Android - kotlin: What is the best way to add a delay in a custom view?
Android - kotlin: What is the best way to add a delay in a custom view?

Time:09-27

I have a custom view let's call it CustomTV, and I need to call notifydatasetchanged after 5 seconds inside method loadDetails(). I know there are 3 ways to do this.

  1. Using Handlers with postdelay. I cannot use this because this is not lifecycle aware safe. the main thread will still execute my Runnable even if there is no View, i.e. user goes the background causing a crash.

  2. Using Observable.timer, I am not 100% sure how this can be done from a View. Where would I dispose the disposable safely?

disposable = Observable.timer( 1000L, TimeUnit.MILLISECONDS, AndroidSchedulers.mainThread() ).subscribe { // myadapter.notifydatasetchanged() }

  1. Coroutines. Issue with this is that I am inside a view. Not sure if I need to have the scope of the fragment of the View or the View.

CodePudding user response:

  1. Is loadDetails() a method in the CustomTV class or in your fragment?

I would suggest using a coroutine in your fragment to update the child view.


Ideally you would push this type of business logic down into a view model and test it - that's probably out of scope for your question though

CodePudding user response:

Regarding 1: I don't think it will cause a crash. The Runnable itself will keep the View reference alive. But this would keep your View alive longer than necessary. Handlers are dangerous when they try to use a Fragment's attached Activity/Context assuming they are not null, because it can be null at the time the Runnable is called.

I don't use Rx, so can't comment on that.

Regarding 3: I would make loadDetails a suspend function with internal delay() call. Then the Fragment or Activity that calls loadDetails() can use its own coroutine launched from its own lifecycleScope to call it. The Fragment can use launchWhenStarted if applicable.

  • Related