refactor code

This commit is contained in:
Eljo 2020-12-14 17:10:50 +01:00
parent 9b56aecce7
commit dc972f2528
1 changed files with 21 additions and 14 deletions

View File

@ -15,9 +15,13 @@ import cash.z.ecc.android.sdk.ext.collectWith
import cash.z.ecc.android.sdk.ext.convertZatoshiToZecString
import cash.z.ecc.android.sdk.tool.DerivationTool
/**
* Displays the available balance && total balance associated with the seed defined by the default config.
* comments.
*/
class GetBalanceFragment : BaseDemoFragment<FragmentGetBalanceBinding>() {
private lateinit var synchronize: Synchronizer
private lateinit var synchronizer: Synchronizer
override fun inflateBinding(layoutInflater: LayoutInflater): FragmentGetBalanceBinding =
FragmentGetBalanceBinding.inflate(layoutInflater)
@ -44,7 +48,7 @@ class GetBalanceFragment : BaseDemoFragment<FragmentGetBalanceBinding>() {
it.importWallet(viewingKey, config.birthdayHeight)
it.server(config.host, config.port)
}.let { initializer ->
synchronize = Synchronizer(initializer)
synchronizer = Synchronizer(initializer)
}
}
}
@ -52,36 +56,39 @@ class GetBalanceFragment : BaseDemoFragment<FragmentGetBalanceBinding>() {
override fun onResume() {
super.onResume()
// the lifecycleScope is used to dispose of the synchronize when the fragment dies
synchronize.start(lifecycleScope)
synchronizer.start(lifecycleScope)
monitorChanges()
}
private fun monitorChanges() {
synchronize.status.collectWith(lifecycleScope, ::onStatus)
synchronize.balances.collectWith(lifecycleScope, ::onBalance)
synchronizer.status.collectWith(lifecycleScope, ::onStatus)
synchronizer.balances.collectWith(lifecycleScope, ::onBalance)
}
private var isSyncing = true
private fun onBalance(balance: CompactBlockProcessor.WalletBalance) {
this.balance = balance
if (!isSyncing) {
binding.textBalance.text = """
Available balance: ${balance.availableZatoshi.convertZatoshiToZecString(12)}
Total balance: ${balance.totalZatoshi.convertZatoshiToZecString(12)}
""".trimIndent()
}
}
private var balance = CompactBlockProcessor.WalletBalance()
private fun onStatus(status: Synchronizer.Status) {
binding.textBalance.text = "Status: $status"
isSyncing = status != Synchronizer.Status.SYNCED
if (status == Synchronizer.Status.SCANNING) {
if (CompactBlockProcessor.WalletBalance().none()) {
binding.textBalance.text = "Calculating balance..."
} else {
if (!isSyncing) onBalance(balance)
onBalance(synchronizer.latestBalance)
}
}
/**
* Extension function which checks if the balance has been updated or its -1
*/
private fun CompactBlockProcessor.WalletBalance.none(): Boolean{
if(synchronizer.latestBalance.totalZatoshi == -1L
&& synchronizer.latestBalance.availableZatoshi == -1L) return true
return false
}
}