-
Notifications
You must be signed in to change notification settings - Fork 128
/
SearchActivity.kt
67 lines (58 loc) · 1.86 KB
/
SearchActivity.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
package com.mindorks.kotlinFlow.learn.search
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import com.mindorks.kotlinFlow.R
import com.mindorks.kotlinFlow.utils.getQueryTextChangeStateFlow
import kotlinx.android.synthetic.main.activity_search.*
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*
import kotlin.coroutines.CoroutineContext
class SearchActivity : AppCompatActivity(), CoroutineScope {
override val coroutineContext: CoroutineContext
get() = Dispatchers.Main + job
private lateinit var job: Job
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_search)
job = Job()
setUpSearchStateFlow()
}
override fun onDestroy() {
job.cancel()
super.onDestroy()
}
private fun setUpSearchStateFlow() {
launch {
searchView.getQueryTextChangeStateFlow()
.debounce(300)
.filter { query ->
if (query.isEmpty()) {
textViewResult.text = ""
return@filter false
} else {
return@filter true
}
}
.distinctUntilChanged()
.flatMapLatest { query ->
dataFromNetwork(query)
.catch {
emitAll(flowOf(""))
}
}
.flowOn(Dispatchers.Default)
.collect { result ->
textViewResult.text = result
}
}
}
/**
* Simulation of network data
*/
private fun dataFromNetwork(query: String): Flow<String> {
return flow {
delay(2000)
emit(query)
}
}
}