Last active
September 11, 2018 06:11
-
-
Save ioKun/115bb4799e0bcbab429aacb13fd8c738 to your computer and use it in GitHub Desktop.
Wrapping java listener with kotlin corutine to return List of data in suspend way
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Wrapper funtion for listener/callback | |
suspend fun hiSearchCameraLan(): Channel<HiSearchSDK.HiSearchResult> { | |
val channel = Channel<HiSearchSDK.HiSearchResult>(Channel.UNLIMITED) | |
launch(UI) { | |
val searchSDK = HiSearchSDK(HiSearchSDK.ISearchResult { result -> | |
if (!result.uid.isEmpty()) | |
channel.offer(result) | |
else | |
channel.close(NullPointerException()) | |
}) | |
searchSDK.search2() | |
channel.invokeOnClose { | |
searchSDK.stop() | |
} | |
} | |
return channel | |
} | |
// Usage | |
fun findCameras(): Either<Failure, List<MyCameraEntity>> { | |
val list = ArrayList<MyCameraEntity>() | |
runBlocking { | |
val hiSearchCameraLan = hiSearchCameraLan() | |
hiSearchCameraLan.consume { | |
hiSearchCameraLan.let<ReceiveChannel<HiSearchSDK.HiSearchResult>, Unit> { cameraChannel -> | |
while (true) { | |
val nextCamera = withTimeoutOrNull(2, TimeUnit.SECONDS) { | |
cameraChannel.receiveOrNull() | |
} ?: break | |
list.add(MyCameraEntity(nextCamera.uid, "", "", nextCamera.name, nextCamera.version)) | |
} | |
} | |
} | |
} | |
return Either.Right(list) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment