Skip to content

Instantly share code, notes, and snippets.

@Qkyyy
Last active September 22, 2021 12:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Qkyyy/ce9a3ba6ac14f034968c078a9588bc66 to your computer and use it in GitHub Desktop.
Save Qkyyy/ce9a3ba6ac14f034968c078a9588bc66 to your computer and use it in GitHub Desktop.
StateFlow problem
binding.productBarcodeInputEditText.textChanges()
.conflate()
.debounce(500)
.filter { it.isNotEmpty() }
.mapNotNull { viewModel.getProductByBarcode(it.toString()) } //api call (repository pattern)
.onEach { viewModel.setProduct(it) }
.launchIn(viewLifecycleOwner.lifecycleScope)
viewModel.product
.filterNotNull()
.onEach {
//some UI updates
}
.launchIn(viewLifecycleOwner.lifecycleScope)
/**
*
* @param id
* @param code
*/
@JsonClass(generateAdapter = true)
@Parcelize
data class Product(
@Json(name = "id")
val id: kotlin.Int? = null,
@Json(name = "code")
//... rest of the parameters which could be other data classes
) : Parcelable
private val _product = MutableStateFlow<Product?>(null)
val product: StateFlow<Product?> = _product
//let's say setProduct is called from Fragment after obtaining it from jetpack's navigation arguments
fun setProduct(product: Product?) {
_product.value = product
}
private suspend fun getProductByBarcode(barcode: String) = productRepository.getProductByBarcode(barcode)
.catch { }
.singleOrNull()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment