is there any better way to write this code? code i...
# android
m
is there any better way to write this code? code in thread
Copy code
private val documentId = MutableStateFlow<String?>(null)
    private val _document = MutableStateFlow<Document?>(null)
    val document: StateFlow<Document?> = _document

    init {
        viewModelScope.launch {
            documentId.collect {
                _document.value = repository.findById(it!!).first()
            }
        }
    }
I tried it but seems something is wrong
Copy code
private val documentId = MutableStateFlow<String?>(null)
val document: StateFlow<Document?> = documentId.filterNotNull().transform {
    repository.findById(it)
}.stateIn(viewModelScope, SharingStarted.Lazily, null)
d
Why is documentId a stateFlow? Can it just be passed as an argument to a function.
Copy code
private val documentId = MutableStateFlow<String?>(null)
val document: StateFlow<Document?> = documentId.filterNotNull().flatMap { id ->
repository.findById(id) 
}.asStateFlow()
u
Copy code
scope.launch {
   id.flatMapLatest {
      if (it == null) {
         flowOf(null)
      } else {
         repo.findById(it}
      }
   }.collect {
      _document.value = it
   }
}