Skip to content

Instantly share code, notes, and snippets.

Avatar

Shivam Dhuria Shivamdhuria

View GitHub Profile
View MainActivity.kt
class MainActivity : AppCompatActivity() {
val textview by lazy { findViewById<View>(R.id.textView) as TextView }
val progressBar by lazy { findViewById<View>(R.id.progressbar) as ProgressBar }
val buttonMusic by lazy { findViewById<View>(R.id.button_music) as Button }
var progressPercentage = 0
private var job: Job? = null
val scope by lazy { CoroutineScope(Dispatchers.Main) }
override fun onCreate(savedInstanceState: Bundle?) {
View activityLifecycle
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
override fun onDestroy(){
super.onDestroy()
}
View BackOffActivity.kt
lifecycleScope.launch {
viewModel.dogImagesFlow.collect {
when (it) {
is ResultWrapper.NetworkError -> {
errorText.append("${it.errorMessage} \n")
...
}
is ResultWrapper.Success<*> -> {
...
showLoading(false)
View BackOffVM.kt
val dogImagesFlow = getDogImages().flowOn(Dispatchers.IO)
.retryWhen { cause, attempt ->
if (cause is IOException && attempt < 3) {
val delay = 2000 * (attempt + 1)
emit(
ResultWrapper.NetworkError(
"Attempt No ${attempt + 1} Failed.Retrying again in time ${delay / 1000} sec...",
delay.toInt()
)
)
View BackOffVM.kt
private fun getDogImages(): Flow<ResultWrapper> {
return flow {
emit(ResultWrapper.Loading(true))
delay(3000)
val randomNumber = (0..5).random()
emit(ResultWrapper.Loading(false))
if (randomNumber < 3) {
throw IOException()
}
emit(ResultWrapper.Success(getList()))
View Activity.kt
search.addTextChangedListener {
viewModel.setSearchQuery(it.toString())
}
lifecycleScope.launch {
viewModel.networkOperationResult.collect { value ->
textView.append(value)
textView.append("\n")
}
}
View DebouceViewModel.kt
private val _searchQuery = MutableStateFlow("")
fun setSearchQuery(query: String) {
_searchQuery.value = query
}
val networkOperationResult: Flow<String> = _searchQuery.debounce(1000).mapLatest {
if (it.isEmpty()) {
return@mapLatest ""
} else {
View DebouceViewModel.kt
@AnyThread
private suspend fun longNetworkOperation(request: String): String =
withContext(Dispatchers.Default) {
delay(1000)
"Pseudo network delay of 3s delay: $request"
}
View ValidationActivity.kt
private fun initListeners() {
editText_name.addTextChangedListener {
viewModel.setFirstName(it.toString())
}
editText_password.addTextChangedListener {
viewModel.setPassword(it.toString())
}
editText_user.addTextChangedListener {
viewModel.setUserId(it.toString())
}
View ValidationActivity.kt
private fun collectFlow() {
lifecycleScope.launch {
viewModel.isSubmitEnabled.collect { value ->
submit_button.isEnabled = value
}
}
}