什么是Kotlin相当于这个Java代码?
doAnswer(new Answer() {
@Override
public Object answer(InvocationOnMock invocation) throws Throwable {
Design design = new Design();
GetDesign.Listener callback = (GetDesign.Listener) invocation.getArguments()[0];
callback.onSuccess(design);
return null;
}
}).when(someRepository).getDesign(any(GetDesign.Listener.class));
Run Code Online (Sandbox Code Playgroud)
[更新]在尝试了几个选项后,我终于使用了mockito-kotlin.我认为这是最舒适的实施方式doAnswer
.语法几乎保持不变:
doAnswer {
callback = it.arguments[0] as GetDesign.Listener
callback.onSuccess(Design())
null
}.whenever(someRepository).execute(any(GetDesign.Listener::class.java))
Run Code Online (Sandbox Code Playgroud)
可以在此处找到完整的代码和build.gradle配置
我发现我的Android App中的这个特定代码阻止了UI线程:
runBlocking {
async(CommonPool) {
Thread.sleep(5000)
}.await()
}
textView.text = "Finish!"
Run Code Online (Sandbox Code Playgroud)
我一直在使用协同程序执行多个任务,并且它们从不阻止UI线程,可以在文档中阅读:
.协同程序提供了一种避免阻塞线程并用更便宜和更可控的操作替换它的方法:协同程序的暂停
但奇怪的是,这段代码:
runBlocking {
async(CommonPool) {
launch(CommonPool) {
Thread.sleep(5000)
runOnUiThread { textView.text = "Finish!" }
}
}.await()
}
Run Code Online (Sandbox Code Playgroud)
表现如预期; 不阻塞,等待五秒然后打印结果(我需要更新UI后,只有在sleep
完成后)
文档说明async
并且launch
可以独立使用,不需要组合.其实async(CommonPool)
应该够了.
那么这里到底发生了什么?为什么它只适用于async+launch
?
我的完整示例代码:
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
button1.setOnClickListener {
runBlocking {
async(CommonPool) {
Thread.sleep(5000L)
}.await()
}
textView1.text = "Finally! I've been blocked for 5s :-("
} …
Run Code Online (Sandbox Code Playgroud) 我正在使用MapsForge最新分支(master),我想实现Marker的onTap事件.我认为它可能在0.3.0,但我不能使用0.3.0,因为我在地图上为每个标记使用不同的Drawable.
ArrayList<Monument> monuments = getMonuments();
mListOverlay = new ListOverlay();
ArrayList<OverlayItem> markers = new ArrayList<OverlayItem>();
for(Monument m : monuments){
GeoPoint gp = new GeoPoint(m.getLat(), m.getLon());
Marker m = createCustomMarker(R.drawable.marker, gp, p.getNumber()));
markers.add(m);
}
mListOverlay.getOverlayItems().addAll(markers);
mMapView.getOverlays().add(mListOverlay);
Run Code Online (Sandbox Code Playgroud)
"createCustomMarker"返回一个标记,该标记使用带有数字的Drawable.
任何人都知道如何轻敲"m"的行为?
记住:分公司高手!不是0.3.0 !!
谢谢