truetime-android icon indicating copy to clipboard operation
truetime-android copied to clipboard

TrueTimeRx initial in Application.onCreate(), where I should add clear() for this disposable?

Open thuypt opened this issue 7 years ago • 2 comments

Regarding example, we got a Disposable at time TrueTimeRx initial in Application.onCreate(), it should be added in a CompositeDisposable like this:

private CompositeDisposable disposables; disposables.add(trueTimeRxDisposable)

Problem is we don't have something like onDestroy in Application layer, so where and when I should call disposables.clear()?

thuypt avatar Jan 11 '19 10:01 thuypt

You don't need to dispose of it. If you call TrueTimeRx in your Application, it means its lifetime is tried to the lifetime of the application, so you never want to stop observing it. When either a successful time or an error comes through the subscription, the subscription will be closed, so you wont need to stop observing it early.

  For cleanliness, I've added the disposables.clear() call in the onTerminate method which would be the Application equivalent of onDestroy.

MarkVillacampa avatar Jan 24 '19 15:01 MarkVillacampa

For cleanliness, I've added the disposables.clear() call in the onTerminate method which would be the Application equivalent of onDestroy.

MarkVillacampa As far as I know, It is not equivalent, because onTerminate isn't always called.

thuypt This is how I handle it with retries:

override fun onCreate() {
        super.onCreate()

        with(ProcessLifecycleOwner.get()) {
            lifecycleScope.launch {
                lifecycle.repeatOnLifecycle(Lifecycle.State.CREATED) {
                    handleTrueTime()
                }
            }
        }
    }


    private fun CoroutineScope.handleTrueTime() = launch {
        var disposable: Disposable? = null
        try {
            while (isActive) {
                disposable?.dispose()
                disposable = TrueTimeRx.build()
                    .initializeNtp(NTP_APPLE)
                    .subscribeOn(Schedulers.io())
                    .subscribe(
                        {
                            // Note that it not always invokes
                            Log.d(
                                TAG,
                                "TrueTime was initialized"
                            )
                        }
                    ) { throwable: Throwable ->
                        // Note that it not always invokes
                        Sentry.captureException(throwable)
                        Log.d(
                            TAG,
                            "TrueTime wasn't initialized: ${throwable}"
                        )
                    }
                delay(DELAY_BETWEEN_CLOCK_RE_SYNC)
            }
        } finally {
            disposable?.dispose()
        }

    }


CyxouD avatar Feb 21 '24 09:02 CyxouD